modifiy values of multiple keys at once in python dictionary - python

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))))

Related

Not able to understand the output for dictionary comprehension in python

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.

Comparing list values to the key values of a dictionary

I have a list of codes
l = [1, 2, 3, 4]
And a dictionary of previously seen codes and their translation
d = {1: 'A', 2: 'B', 3: 'C' }
I am trying to compare the list values to the dict key and create a new dict with the dict values of the matches. I accomplished this with the code below:
x = {k: d[k] for k in l if k in d}
However I also want to keep the list values that don't appear in the existing dict because these it is important to track new values. I would like to store these in the new dict with the val being 'no match' or something. I am not sure how to do this in a pythonic way.
Final dict:
{1: 'A', 2: 'B', 3: 'C', 4: 'no match'}
I know that this can be done by creating a dataframe from the dictionary and a dataframe from the list & outer joining but I would like to get better at dictionaries if possible!
You can use dict.get(), which can take a default value that is returned in case the key is not found in the dictionary:
x = {k: d.get(k, 'no match') for k in l}

Can't crate a dictionary from two lists using dictionary comprehension with two FORs. Why?

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))

Combine 2 dictionaries by key-value in python

I have not found a solution to my question, yet I hope it's trivial.
I have two dictionaries:
dictA:
contains the order number of a word in a text as key: word as value
e.g.
{0:'Roses',1:'are',2:'red'...12:'blue'}
dictB:
contains counts of those words in the text
e.g.
{'Roses':2,'are':4,'blue':1}
I want to replace the values in dictA by values in dictB via keys in dictB, checking for nones, replacing by 0.
So output should look like:
{0:2,1:4,2:0...12:1}
Is there a way for doing it, preferentially without introducing own functions?
Use a dictionary comprehension and apply the get method of dict B to return 0 for items that are not found in B:
>>> A = {0:'Roses',1:'are',2:'red', 12:'blue'}
>>> B = {'Roses':2,'are':4,'blue':1}
>>> {k: B.get(v, 0) for k, v in A.items()}
{0: 2, 1: 4, 2: 0, 12: 1}

Is there a method like append for dictionaries [duplicate]

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.

Categories

Resources