Python: How to change dictionary values ​​in a for loop alternating keys?

I am new to Python (and programming).

I would like to change the dictionary in a for loop, alternating the dictionary key. However, I wrote the following code, which was unsuccessful:

#coding: utf-8
dict1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dict2 = dict.fromkeys(dict1.values(),[])

for key in dict2:
    if key == 'value1':
        dict2[key].extend(['test1', 'test2'])
    elif key == 'value2':
        dict2[key].extend(['test3', 'test4'])
    elif key == 'value3':
        dict2[key].extend(['test5', 'test6'])

print (dict2['value1'])
print (dict2['value3'])

I expected the results to be as follows:

 ['test5', 'test6']
 ['test1', 'test2']

but I really got:

 ['test5', 'test6', 'test3', 'test4', 'test1', 'test2']
 ['test5', 'test6', 'test3', 'test4', 'test1', 'test2']

I think the problem is that I made a dictionary from another dictionary using "dict.fromkeys", but I could not understand why this is problematic, even if it is.

Thank you for the attention. Wait for your offers.

+3
source share
5 answers

All values dict2are actually the same instance of the list, because passing []in dict.fromkeys()creates only one instance of the list. Try

dict2 = dict((v, []) for v in dict1.values())
+6

, . .

Python2> dict1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Python2> dict2 = dict.fromkeys(dict1.values(),[])
Python2> dict2
{'value1': [], 'value2': [], 'value3': []}
Python2> dict2['value1']
[]
Python2> id(dict2['value1'])
43895336
Python2> id(dict2['value2'])
43895336
Python2> id(dict2['value3'])
43895336

, .

+2

yourdict.keys() ( , - dict)

0

, dict.fromkeys() .

dict2 = dict((x, []) for x in dict1.values())
0

, , dict.fromkeys() , . , dict2 a defaultdict collections list:

from collections import defaultdict

dict1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dict2 = defaultdict(list)

for key in dict1.itervalues():
    if key == 'value1':
        dict2[key].extend(['test1', 'test2'])
    elif key == 'value2':
        dict2[key].extend(['test3', 'test4'])
    elif key == 'value3':
        dict2[key].extend(['test5', 'test6'])

print dict2['value1']
# ['test1', 'test2']
print dict2['value3']
# ['test5', 'test6']
0

All Articles