Suppose I have the following Python dictionary:
letters= {0: 'a',
1: 'b',
2: 'c',
3: 'd',
4: 'e',
5: 'f',
6: 'g',
7: 'h',
8: 'i',
9: 'j',
10: 'k',
11: 'l',
12: 'm',
13: 'n',
14: 'o',
15: 'p',
16: 'q',
17: 'r',
18: 's',
19: 't',
20: 'u',
21: 'v',
22: 'w',
23: 'x',
24: 'y',
25: 'z',
26: ' '}
And I change the order of the keys and values with the following dict comprehension:
encoding = {y:x for x,y in letters.items()}
The next thing I want to do is that, for each letter (key), its value is increased by 3 using the following:
ek= 3
That way, we would have:
'a': 3
'b': 4
and so on.
How can I achieve that without having to do it manually? I would like to put some idea but these two approaches were not successful:
encoding= {sum(ek) for x in encoding.values()}
TypeError: 'int' object is not iterable
encoding.update(sum(ek) in encoding.values())
TypeError: 'int' object is not iterable
Any help will be greatly appreciated. Cheers!
You can do it directly in the creation of
encoding
, adding the variableThe built-in function
sum
receives an iterable and returns the sum of its items by iterating over it. You are passing the values from the dictionary, which are integers, hence the error (you cannot iterate over an integer).If you don't want to do the addition on creation
encodig
you can use a loopfor
to modify the 'in-place' values later:Or using
dict.update
:Either way, the output is: