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?

Asked By: mempy

||

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)
Answered By: Ewan Brown

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}
Answered By: C-Gian
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]
Answered By: atrocia6

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()}
Answered By: Tytrox
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.