a=[1,2,4]
dict={1:"k",2:"r",3:"t",4:"y",5:"z"}
list "a" has to be searched with dict key. If match is found then those values have to be copied to a new dictionary as shown below:
new_dict={1:"k",2:"r",4:"y"}
a=[1,2,4]
dict={1:"k",2:"r",3:"t",4:"y",5:"z"}
list "a" has to be searched with dict key. If match is found then those values have to be copied to a new dictionary as shown below:
new_dict={1:"k",2:"r",4:"y"}
You can use dict comprehension
like below
a=[1,2,4]
d={1:"k",2:"r",3:"t",4:"y",5:"z"}
new_dict = {i:d.get(i) for i in a}
print(new_dict)
Output:
{1: 'k', 2: 'r', 4: 'y'}
In above solution if key is not present in original dict, it takes value as None
.
I'll try and help you with the thinking process for a naive solution:
We can iterate through the dict's items and check if the keys are present in the list. If so, add the item to a new dict:
a = [1, 2, 4]
d = {1: "k", 2: "r", 3: "t", 4: "y", 5: "z"}
new_d = {}
for k,v in d.items():
if k in a:
new_d[k] = v
Alternatively, iterate through a
and if the element is a key in the dict, add the corresponding item to a new dict:
a = [1, 2, 4]
d = {1: "k", 2: "r", 3: "t", 4: "y", 5: "z"}
new_d = {}
for k in a:
if k in d:
new_d[k] = d[k]
This however is probably the faster, better solution as searching in a dict is O(1)
while searching in a list is O(N)
. So even if the list is bigger than the dictionary, it will still be preferable.
Try:
from operator import itemgetter
a=[1,2,4]
dict_={1:"k",2:"r",3:"t",4:"y",5:"z"}
reduce a
to only keys, that exist in dict_
:
a=set(a).intersection(dict_.keys())
itemgetter
will get values from a
, then you re-merge them using zip
with a
to make filtered dict
:
dict_2=dict(zip(a,itemgetter(*a)(dict_)))
Output:
{1: 'k', 2: 'r', 4: 'y'}