Python - add key-value pair to dictionary in array [duplicate] - python

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 7 years ago.
Question is in title. I can't make it work:
>>> data = [{}] * 2
>>> data[1].update({3:4})
>>> data
[{3: 4}, {3: 4}]
key-value pair adds to all elements of array. I expected to receive that:
[{}, {3: 4}]

The problem is that
data = [{}] * 2
Creates a list that has the same dictionary in it twice.
To illustrate this, let's look at id(data[0]) and id(data[1]):
>>> data = [{}] * 2
>>> data
[{}, {}]
>>> id(data[0])
4490760552
>>> id(data[1])
4490760552
Note that id(data[0]) and id(data[1]) are the same because both entries in the list refer to the same object
What you probably want is
>>> d2 = [{} for i in range(2)]
>>> d2[0][4] = 'a'
>>> d2
[{4: 'a'}, {}]

Instead of using:
data = [{}] * 2
data[1].update({3:4})
print data
which adds the same dictionary to your list, use this instead:
data = [{}, {}]
data[1].update({3:4})
print data
data[1] now means the second {} in your list. The result of this program is:
[{}, {3: 4}]
Why doesn't data = [{}] * 2 work? Because it you are making the same thing twice, which means you are forced to replace both {} with {3:4} which gives you the result you had. With data = [{}, {}], you can only change the second dictionary since data[0] is the first one and data[1] is the next item and so on.

The problem is, that you added the same dictionary twice to your list.
The trouble is already in your first statement:
data = [{}] * 2
This creates a list with two times the same entry. When you update one of those, the update will be visible in both entries of the list.
Try this:
data = [ {} for i in range(2) ]
When you now do your update, you will get your expected result.

Related

Why does setting a key/value pair of list of dictionaries fill all dictionaries? [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 1 year ago.
test = [{}]*5 # Creates [{}, {}, {}, {}, {}]
print(test[1]) # outputs "{}"
test[1]['asdf'] = 5
print(test)
This gives test as [{'asdf': 5}, {'asdf': 5}, {'asdf': 5}, {'asdf': 5}, {'asdf': 5}]. Somehow, all the dictionaries in the list have been set to the same value
But this doesn't happen if we initialize the list a different way:
test2 = [{} for i in range(5)] # Also [{}, {}, {}, {}, {}]
test2[1]['asdf'] = 1
print(test2)
test2 now equals [{}, {'asdf': 1}, {}, {}, {}], the expected result.
The difference between the two is that for [{}]*5, Python creates a 5 element list containing the dictionary given in the square brackets. Ie. it's 5 different references to the same dictionary.
While the other method creates a new dictionary for every element in the list.
More detailed explanation can be found in the duplicate question link

python list append method do not return expected results?

This is the code:
def appd():
atho = []
data = {'snm':None}
for i in range(5):
data['snm'] = i
atho.append(data)
return atho
I expect that the result will be like this:
[{'snm': 0}, {'snm': 1}, {'snm': 2}, {'snm': 3}, {'snm': 4}]
but the result I got in python 3 platform is:
[{'snm': 4}, {'snm': 4}, {'snm': 4}, {'snm': 4}, {'snm': 4}]
How does that happen?
A dictionary cannot have identical keys. So, every time you are doing data['snm'] = i you are replacing the value. Also, your append adds the same dictionary every time, not a copy. So, you list does not have 5 dictionaries, it has 5 references to the same dictionary. And, when it changes, all positions of your list change.
Short fix: add a new dict every time
for i in range(5):
atho.append({'snm': i})
Dictionary cannot hold duplicate keys. If you try adding duplicates, the last added value is added to the key.
>>> d = {'a': 1}
>>> d['a'] = 2
>>> d['a'] = 3
>>> d
{'a': 3}
>>>
With data['snm'] = i, you are basically doing the same thing and this dictionary is being added to list using append.
To fix it, define data = {} inside your loop, so every time you create a new dictionary before appending.
def appd():
atho = []
for i in range(5):
data = {}
data['snm'] = i
atho.append(data)
return atho
print(appd())
You are inserting the same dictionary again and again, instead of inserting a new dictionary whose key is snm.
On each iteration of the range, you are updating the value of the dictionary, therefore it gets updated for all the elements in the list, because all of them point to the same dictionary instance.
You must create a new dictionary on each iteration and then insert it.
Try this:
def appd():
atho = []
for i in range(5):
atho.append({'snm':i})
return atho
If you reuse the same oject, again and again, you are simply updating it's contents. The trick is either to explicitly copy the object or create a new one. You cannot simply keep overriting the same key and expect different values
You are actually appending a reference to the original dictionary.
The result you are seeing is the last iteration of your loop updating the dictionary, and thus all its references in your list.
Using atho.append(data.copy()) will work.

Index dictionaries inside a list [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Create list of single item repeated N times
(9 answers)
Closed 5 years ago.
I have a list of dictionaries:
dicty = [defaultdict(list)] * (2)
dicty
[defaultdict(list, {}), defaultdict(list, {})]
Now I want to know how to index into these dictionaries?
I have tried:
dicty[0][0].append('abc')
dicty
[defaultdict(list, {0: ['abc']}), defaultdict(list, {0: ['abc']})]
But as you can see that it appends in both the dictionaries. I want to learn how to append into an individual dictionary.
You can use:
dicty = [defaultdict(list) for _ in range(2)]
When using [defaultdict(list)] * (2), all your dicts point to the same object in memory.
from collections import defaultdict
""" Here, you are saying that you wish to add twice "defaultdict(list)".
These are the same objects. You are just duplicating the same one with *
"""
dicty = [defaultdict(list)] * (2)
dicty[0][0].append('abc')
print dicty
print dicty[0] is dicty[1], '\n'
""" However, here : you are creating two distinct dictionnaries.
"""
dicty = []
for _ in range(2):
dicty.append(defaultdict(list))
dicty[0][0].append('abc')
print dicty
print dicty[0] is dicty[1]
# outputs :
#[defaultdict(<type 'list'>, {0: ['abc']}), defaultdict(<type 'list'>, {0: ['abc']})]
#True
#[defaultdict(<type 'list'>, {0: ['abc']}), defaultdict(<type 'list'>, {})]
#False

Python: How to get the updated dictionary in 1 line? [duplicate]

This question already has answers here:
How do I merge two dictionaries in a single expression in Python?
(43 answers)
Closed 6 years ago.
In python, I have a dictionary named dict_a :
dict_a = {'a':1}
and I want to get a new dictionary dict_b as the update of dict_a,at the same time I don't want to change the dict_a, so I used this:
dict_b = copy.deepcopy(dict_a).update({'b':2})
However, the return value of dict.update is None, so the above code doesn't work. And I have to use this:
temp = copy.deepcopy(dict_a)
temp.update({'b':2})
dict_b = temp
The question is, how to get my goal in one line? Or some
What about:
>>> a = {'a':1}
>>> update = {'b': 1}
>>> b = dict(a.items() + update.items())
>>> b
{'a': 1, 'b': 1}
update - is your value that need to update(extend) dict a
b - is a new resulting dict
Anfd in this case a stay unchanged

syntax for creating a dictionary into another dictionary in python [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
syntax to insert one list into another list in python
How could be the syntax for creating a dictionary into another dictionary in python
You can declare a dictionary inside a dictionary by nesting the {} containers:
d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}
And then you can access the elements using the [] syntax:
print d['dict1'] # {'foo': 1, 'bar': 2}
print d['dict1']['foo'] # 1
print d['dict2']['quux'] # 4
Given the above, if you want to add another dictionary to the dictionary, it can be done like so:
d['dict3'] = {'spam': 5, 'ham': 6}
or if you prefer to add items to the internal dictionary one by one:
d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8
dict1 = {}
dict1['dict2'] = {}
print dict1
>>> {'dict2': {},}
this is commonly known as nesting iterators into other iterators I think
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

Categories

Resources