Setting a value to a dictionary's dictionary value - python

The code:
>>> mydict = {}
>>> keylist = ['a','b','c']
>>> mydict=dict.fromkeys(keylist,{})
>>> mydict['a']['sample'] = 1
>>> mydict
{'a': {'sample': 1}, 'c': {'sample': 1}, 'b': {'sample': 1}}
I was expecting mydict['a']['sample'] = 1 would set the value just for a's dictionary value and would get this: {'a': {'sample': 1}, 'c': {}, 'b': {}}.
What am I missing here? What should I have to do to get the expected output?

The problem is that you added the same dictionary to mydict for every key. You want to add different dictionaries, like so:
mydict = dict((key, {}) for key in keylist)
In the above code, you create a new dictionary to pair with each key. In your original code, the function fromkeys took the argument (the empty dictionary you provided) and added that exact argument - that single empty dictionary you created to pass in to the function - to each of the keys. When that one dictionary was changed, then, that change showed up everywhere.

Related

Duplicate dictionary keys in initialization - Python

Is it correct to say that the rightmost/last key-value pair for a given key would always be considered if there are multiple identical keys when initializing a dictionary ?
Example :
Dict = {'A': 5, 'B': 6, 'A': 10}
Will Dict['A'] always be 10 in all python implementations? Where does python enforce this ?
You know that python dict can't contain duplicate keys. So
Dict = {'A': 5, 'B': 6)
Dict.update({'A': 10})
print(Dict['A'])
will result in the last value assigned to the key A:
Output:
10
So the situation is almost like that, python goes through the dictionary during evaluation, and keeps the last value assigned to the keys.
I know dict aren't ordered, but:
That doesn't mean python will jump back and forth on the dict when parsing the dict into memory.
It will parse through it from left to right to get the collect the data, but it stores the dict without keeping its order.
Python dict can not have duplicate keys. if you try to add the same key again, it will update the existing key with the new value.
Dict = {'A': 5, 'B': 6, 'A': 10}
print(Dict)
{'A': 10, 'B': 6}
the above statement execution is similar to below:
Dict['A'] = 5
print(Dict)
{'A'=5}
Dict['B'] = 6
print(Dict)
{'A'=5, 'B'=6}
Dict['A'] = 10
print(Dict)
{'A'=10, 'B'=6}

What does defaultdict(list, {}) or dict({}) do?

I saw this online and I'm confused on what the second argument would do:
defaultdict(list, {})
Looking at what I get on the console, it seems to simply create a defaultdict where values are lists by default. If so, is this exactly equivalent to running defaultdict(list)?
From I read online:
The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.
which also makes me wonder about the difference between:
my_dict = dict({})
my_dict = dict()
the argument to the dict class in python is the instantiation values.. so passing an {} creates an empty dictionary.
Its the same case with defaultdict, except that the first argument is the default type of the values for every key.
dict({...}) just makes a dict:
>>> dict({'a': 1, 'b': 2})
{'a': 1, 'b': 2}
Which is equal to this:
>>> dict(a=1, b=2)
{'a': 1, 'b': 2}
or
>>> {'a': 1, 'b': 2}
{'a': 1, 'b': 2}
The same applies for defualtdict.

Insertion order and Duplicate Keys in Dictionary

I'm using python 3.7.
I have a dictionary something like this.
dict = { 'a' :2 , 'a' :1 , 'b':3 , 'c':4}
print(dict)
O/P ={'a' : 1 , 'b' :2 , 'c':3 }
Now In python 3.7 dictionary must maintain insertion order .So expected o/p will be {'a':2 , 'b':3 , 'c' :4} , but ('a',2) is being removed from dictionary instead of('a',1) .Why is this happening ??Is there any rule for removing duplicate keys in python ??
From the Python documentation:
The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
See: https://docs.python.org/3/tutorial/datastructures.html
Maintaining insertion order is concerned with different keys:
>>> dct = {'a': 1, 'b': 2} # do NOT shadow built-in name 'dict'
>>> print(dct)
{'a': 1, 'b': 2}
# and not
{'b': 2, 'a': 1} # which was totally possible before Python3.6
When receiving multiple values for the same key, the last one provided wins:
>>> dct = {'a': 3, 'a': 1, 'b': 2}
>>> print(dct)
{'a': 1, 'b': 2}
This is similar to the following scenario:
>>> dct = {}
>>> dct['a'] = 3
>>> dct['a'] = 1
>>> dct['b'] = 2
Would you expect dct['a'] to be 3 now because of the "insertion order"? Certainly not!
The value assigned to a key can be anything and even duplicated since it merely a value. Keys however, are similar to a variable name. Like in many programming languages, if a variable name is used again in the same scope or method, the first variable and its value is overwritten by the second since it is more recent.
In this case it may be more appropriate to to assign a different key (think of keys as identifiers) to the same value if that is your wish. Like this
dict = { 2: 'a', 1: 'a', 3:'b', 4:'c'}
print(dict)
O/P = {1: 'a', 2: 'a', 3: 'b', 4: 'c'}

python update dictionary with dictionary in loop

I am trying to update a dictionary with an other dictionary in a loop
mainDict = {}
for index in range(3):
tempDict = {}
tempDict['a'] = 1
tempDict['b'] = 2
mainDict.update(tempDict)
Output:
>>> print mainDict
{'a': 1, 'b': 2}
What I am expecting is:
{{'a': 1, 'b': 2},{'a': 1, 'b': 2},{'a': 1, 'b': 2}}
Any suggestions please. Thanks.
Dictionaries are key-value pairs. In your expected output there is no dictionary. Either you want a list, and in this case use:
main_list = []
for (...)
main_list.append(temp_dict)
or add keys in the loop:
mainDict = {}
for index in range(3):
tempDict = {}
tempDict['a'] = 1
tempDict['b'] = 2
mainDict[index] = tempDict
As others commented in the comments section, python dictionaries keys must be unique. Quoting from python docs:
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)
Possible solution: Create a list instead of a dict to store the dictionaries.

Append Key and Value to a Key Value pair Dictionary Python

My intended goal is to append a key value pair to a value in inside of a dictionary:
I have the following:
crucial = {'C': {'C': 0, 'B': 1}}
done = {}
for each in crucial:
for i in each:
done['D'] = 0
print(done)
print(crucial[i].append(done))
The output is:
Traceback (most recent call last):
File "C:\Users\User\Documents\Programming Full-Stack\Python\Exercise Files\02 Quick Start\conditionals.py", line 13, in <module>
print(crucial[i].append(done))
AttributeError: 'dict' object has no attribute 'append'
{'D': 0}
Expected output:
{'C': {'C': 0, 'B': 1, 'D':0}}
Therefore, can anyone provide me a guideline to append a key value pair to that value field in the outer dictionary?
Different approaches tried: So far I've tried converting the dictionary to a list declaring d as [], not with {}. I also tried putting .extend instead of .append. But in none of those cases I've got the result I wanted.
Thank you in advance
As the error states, dict has no attribute append. There is no append method in the dictionary object. To assign a value to a particular key in a dictionary, it is simply:
d[key] = new_value
where new_value can be, if you wish: {'a':1}
If you are looking to update your dictionary with new data, you can use the update method.
d.update(new_stuff)
In your code, simply change your append, similar to the example I provided. I corrected it here:
crucial = {'C': {'C': 0, 'B': 1}}
done = {}
for each in crucial:
for i in each:
done['D'] = 0
print(done)
crucial[i].update(done)
print(crucial)
Python has a update function to add new items to dictionary
crucial .update({'D':'0'})

Categories

Resources