-1
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"}
Sociopath
  • 13,068
  • 19
  • 47
  • 75
Gurpreet
  • 37
  • 5
  • 3
    Have you tried anything at all and have a problem with something specific? – Tomerikoo Jan 23 '20 at 19:05
  • 2
    Please read [how to ask](https://stackoverflow.com/help/how-to-ask) – Pynchia Jan 23 '20 at 19:16
  • Possible duplicate of [Filter dict to contain only certain keys?](https://stackoverflow.com/questions/3420122/filter-dict-to-contain-only-certain-keys) – jpp Jan 23 '20 at 19:45

3 Answers3

2

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.

Sociopath
  • 13,068
  • 19
  • 47
  • 75
  • 1
    Good solution. Given the question, expound why it is convenient (I can think of two reasons on the spot). However, please specify your solution assumes all the keys are present in `d`, otherwise it fails – Pynchia Jan 23 '20 at 19:19
  • @Pynchia thanks for pointing out. I think `get` is better option is such a case – Sociopath Jan 23 '20 at 19:32
0

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Please explain the reasons why the first solution isn't optimal. The second one is better and it copes with keys that may be absent from the dictionary (It may not be necessary, but the question formulates its assumptions poorly) – Pynchia Jan 23 '20 at 19:26
0

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'}
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34