Select key and one value out of tuples with multiple values per key to create new dictionary
Question:
I started recently learning programming Python and I am running into a problem. I tried to solve this myself, unsuccessfully.
I have a dictionary with a formatted string as a key and tuples with 3 values per key.
dict1 = { “a;2;1;1;” : ( 1, 2, 3), “a;3;2;1;” : ( 4, 5, 6)}
I want to create a new dictionary dict2 with all keys from dict1 and only the third value from each key.
dict2 = { “a;2;1;1;” : 3, “a;3;2;1;” : 6}
In these examples I used only two key-value pairs, the real dictionary has ten thousand of key-value pairs.
Any suggestions?
Answers:
2 Line solution, could probably be done in a more ‘python’ way but this will work:
dict1 = {'a;2;1;1;' : ( 1, 2, 3), 'a;3;2;1;' : ( 4, 5, 6)}
dict2 = {}
# You just need these two lines here
for k in dict1:
dict2[k] = dict1[k][2]
print(dict2)
Do it with a simple iteration:
dict2 = dict()
for k in dict1:
dict2[k] = dict1[k][2]
Or use a dict-comprehension to do it in a single line:
dict2 = {k: dict1[k][2] for k in dict1}
dict1 = { 'a;2;1;1;' : ( 1, 2, 3), 'a;3;2;1;' : ( 4, 5, 6)}
dict2 = {}
for k in dict1.keys():
dict2[k] = dict1[k][2]
This can be done with a dictionary comprehension also:
dict1 = { “a;2;1;1;” : ( 1, 2, 3), “a;3;2;1;” : ( 4, 5, 6)}
dict2 = {x: y for (x,(_,_,y)) in dict1.items()}
I started recently learning programming Python and I am running into a problem. I tried to solve this myself, unsuccessfully.
I have a dictionary with a formatted string as a key and tuples with 3 values per key.
dict1 = { “a;2;1;1;” : ( 1, 2, 3), “a;3;2;1;” : ( 4, 5, 6)}
I want to create a new dictionary dict2 with all keys from dict1 and only the third value from each key.
dict2 = { “a;2;1;1;” : 3, “a;3;2;1;” : 6}
In these examples I used only two key-value pairs, the real dictionary has ten thousand of key-value pairs.
Any suggestions?
2 Line solution, could probably be done in a more ‘python’ way but this will work:
dict1 = {'a;2;1;1;' : ( 1, 2, 3), 'a;3;2;1;' : ( 4, 5, 6)}
dict2 = {}
# You just need these two lines here
for k in dict1:
dict2[k] = dict1[k][2]
print(dict2)
Do it with a simple iteration:
dict2 = dict()
for k in dict1:
dict2[k] = dict1[k][2]
Or use a dict-comprehension to do it in a single line:
dict2 = {k: dict1[k][2] for k in dict1}
dict1 = { 'a;2;1;1;' : ( 1, 2, 3), 'a;3;2;1;' : ( 4, 5, 6)}
dict2 = {}
for k in dict1.keys():
dict2[k] = dict1[k][2]
This can be done with a dictionary comprehension also:
dict1 = { “a;2;1;1;” : ( 1, 2, 3), “a;3;2;1;” : ( 4, 5, 6)}
dict2 = {x: y for (x,(_,_,y)) in dict1.items()}