the output for the code:
dict={k:v for k in range(1,4) for v in range(1,3) }
print(dict)
out put is:
{1: 2, 2: 2, 3: 2}
but thought the output should be:
{1: 1, 2: 1, 3: 1}
why is it taking 2 for the value of v.
Python lets you use the same key multiple times in a dictionary comprehension, but obviously the final dictionary can only contain the key once. The associated value is the last one you specified, as per the Python reference manual, 6.2.7 Dictionary Displays:
When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.
Related
I know that there are a bunch of ways to make a dictionary out of two lists, but I wanted to do it using two FOR loops to iterate over both lists. Therefore, I used the following code. Surprisingly, the code doesn't iterate over the second list that contains the values of the dictionary keys and only considers the last element of the list as the value.
key = ['hello', 'mello', 'vello']
value = [1, 2, 3]
dictionary = {k: v for k in key for v in value}
print('dictionary is ', dictionary)
the result was:
dictionary is: {'hello': 3, 'mello': 3, 'vello': 3}
But I expect that the result would be:
dictionary is: {'hello': 1, 'mello': 2, 'vello': 3}
I appreciate it if anyone can clarify this for me.
My understanding is the full dictionary is being recreated each loop with each number as the key, resulting in only your final output being that of the last value (best shown by reversing your key and value statements, returning {1: 'vello', 2: 'vello', 3: 'vello', 4: 'vello'}
If the other is your intended output, this should work fine:
dictionary = dict(zip(key,value))
You can use zip for this purpose.
dictionary = dict(zip(keys, values))
Is it possible to change the values of multiple keys at once without the loop?
d = {1: 0, 2: 0, 3: 0}
for k in [1,2]:
d[k] += 1
If all you want to do is replace values, then you can use dict.update:
d = {1:0, 2:0, 3:0}
d.update({1:1, 2:1})
# {1: 1, 2: 1, 3: 0}
but as far as I know, there's no way to make a custom change without using a loop of some sort. You could use a list comprehension to make a new dict to feed to .update(), doing it all in one line:
d.update({k: d[k] + 1 for k in [1, 2]})
but I don't think there's a general solution for modifying the dict in-place in this way.
Should be able to use a dictionary's update method, just include the keys you want to update and the values you want them to have.
mydict.update(dict(zip(keys, mytupleValues))))
I am looking to merge two dictionaries with the key as months and the values as a list of 12 values in both dictionaries. How do I merge the two dictionaries so that it does not sort into alpha order based on key. I simply want to add my second dictionary (with months June - December as keys) onto the end of my first dictionary (with months January to May as keys).
I have tried using the .concat and .append but I seem to be doing something wrong and it is sorting values.
Thanks
Use update function:
a = {1: 2, 2: 3}
b = {3: 4, 4: 5}
a.update(b)
a
{1: 2, 2: 3, 3: 4, 4: 5}
P.S. Note that dictionaries in Python are unordered. You can't rely on the keys order. If you want to use the ordered dictionary, you should use OrderedDict from collections module.
I have two dictionaries of slightly differing formats and I want to convert one to look like the other so that I can compare them easily. Any pointers to help acheive this would be appreciated.
Dict 1 --> {Key:[{key 1 : value: 1, key 2: value2}, {key 3: value 3, key 4: value 4}]}
Dict 2 --> {Key: { VALUE : [{key 1 : value: 1, key 2: value2}, {key 3: value 3, key 4: value 4}]}}
It seems the only difference between the two dictionaries is that the second one has an extra dict with key VALUE. You could change it to look like the first one by executing:
dict2[Key] = dict2[Key][VALUE]
If you want to change the first dict to look like the second one, you could execute:
dict1[Key] = {VALUE: dict1[Key]}
Try this:
dict2[Key]=dict2[Key][VALUE]
Taking dict_1's structure to be the one you want (might be easier to use):
d_3 = {}
d_3[key] = dict_2[key][VALUE]
You can convert the first dict to the second dict by executing this:
dict3[Value]=dict1[Key]
dict2[Key]=dict3
This question already has answers here:
Most Pythonic Way to Build Dictionary From Single List
(2 answers)
Closed 9 years ago.
How do i add key,value to a dictionary in python?
I defined an empty dictionary and now I want to pass a bunch of keys from a list and set their value as 1. From what I did it creates me every iteration a new dictionary, but I want to append the key,value so eventually I will recieve only one dictionary.
this is my code:
def count_d(words):
count_dict={}
words_set= set(words)
for i in words_set:
count_dict[i]= 1
print (count_dict)
What you are looking for is dict.fromkeys along with dict.update.
From the docs
Create a new dictionary with keys from seq and values set to value.
Example Usage
>>> d = {}
>>> d.update(dict.fromkeys(range(10), 1))
>>> d
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1}
Note, you need an dict.update along with dict.fromkeys, so as to update the dictionary in-place
Instead, if you want to create a dictionary and assign use the notation
>>> d = dict.fromkeys(range(10), 1)
>>> d
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1}
Unfortunately, for in-place update, you need to create a throw-away dictionary before passing to the dict.update method. A non-intuitive method is to leverage itertools
from itertools import izip, repeat
d.update(izip(xrange(10), repeat(1)))
The same idea can be extended to OrderedDict which is often used, as an alternate for OrderedSet as standard library does not provide one.
the fromkeys method does what you want:
count_dict = dict.fromkeys(words_set, 1)
This gives count_dict it's keys from words_set, each with value of 1.
More info on fromkeys here
How do i add key,value to a dictionary in python?
Exactly as you are:
count_dict[i] = 1
From what I did it creates me every iteration a new dictionary
No it doesn't. It keeps appending to the same iteration. The problem is that you print the dictionary-so-far on every iteration.
So, you were very close to what you wanted. I believe that all you want to do is unindent the print statement, so it only happens once at the end, instead of each time through the loop:
def count_d(words):
count_dict={}
words_set= set(words)
for i in words_set:
count_dict[i]= 1
print (count_dict)
Of course it will probably be a lot more useful to return count_dict, not print it. And Abhijit's answer shows a much simpler way to do this. (Another simple way to do it: count_dict = dict(collections.Counter(words_set)). But I think dict.from_keys is more meaningful in this case, despite your variable names.)
But I think this is the part you were actually struggling with.