I have a dictionary of key: value pairs and a list of keys as below:
dict1 = {'a':(1, 2), 'b':(2,2), 'c':(3,3), 'd':(4,4)}
list1 = ['a', 'c']
I now want to create a new dictionary that only contains the key:value pairs taken from list1. So the end result is list2 below:
list2 = {'a':(1, 2), 'c':(3,3)}
Help would be much appreciated. I'm currently using python 2.5.4 if that makes any difference?
Thank you in advance. Tom
one nice expression, even in 2.5 you have a simple solution
dict((k, dict1[k]) for k in list1)
dict
has an initializer that takes an iterable of tuples. The inner expression produces one tuple at a time, looking over the keys in list1
and getting the values from dict1
The above will result in a KeyError
if list1
contains a key not in dict1
, if that's the case then the below will work by looking at the keys in the dict and checking for its presence in list1
dict((k, v) for k, v in dict1.iteritems() if k in list1)
You could do this:
dict2 = {}
for key in list1:
dict2[key] = dict1[key]
(I renamed list2
to dict2
, it seemed to make more sense).
Something like this :
new_dict = {}
for i in list1:
new_dict[i] = dict1[i]
You can do this with a simple loop:
result = {}
for item in list1:
result[item] = dict1[item]
Or, in 2.7+, with a dict comprehension:
result = {key: value
for key, value in dict1.items()
if key in list1}
Just do something simple like:
for item in list1:
list2[item] = dict1[item]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.