I started recently with 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 keys 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 en 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 a two key-value pair, the real dictionary has ten thousands of key-value pairs.
Any suggestions? Help is appreciated.
CodePudding user response:
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)
CodePudding user response:
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}
CodePudding user response:
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]
CodePudding user response:
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()}
CodePudding user response:
Thanks a lot, it works perfectly. Many thanks for the quick response. You just made my day!!!
