1

I have a list full of variable names and a dictionary with names and their ID's.

Example:

name=['name1','name2'....'name20']

dicti={'1':'name1', '2':'name2','hello':'world",'animal':'dog',...'20':'name20'}

What i want is to search the dictionary with elements from the list. If the list element exist in dictionary then don't delete it.

I got this code

for i in dicti.values() :
    for j in name :
        if j != i :
            del dicti[i]
        else :
            continue

When i run the code i got this error:

KeyError: 'name1'

and it cannot delete the element i want.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Alex
  • 1,816
  • 5
  • 23
  • 39
  • so delete everything else apart from the ones in the list. Right? – Ma0 Jan 13 '20 at 08:39
  • Does this answer your question? [Filter dict to contain only certain keys?](https://stackoverflow.com/questions/3420122/filter-dict-to-contain-only-certain-keys) – Sayse Jan 13 '20 at 08:45

2 Answers2

4

Using a dict comprehension

Ex:

name=set(['name1','name2','name20'])
dicti={'1':'name1', '2':'name2','hello':'world','animal':'dog',20:'name20'}
print({k:v for k, v in dicti.items() if v in name})

Output:

{20: 'name20', '1': 'name1', '2': 'name2'}
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

You can use filter() here.

name=['name1','name2'....'name20']
dicti={'1':'name1', '2':'name2','hello':'world",'animal':'dog',...'20':'name20'}
new_dict=dict(filter(lambda x: x[1] in name,dicti.items()))
print(new_dict)

output

{'1': 'name1', '2': 'name2',... 20: 'name20'}
Ch3steR
  • 20,090
  • 4
  • 28
  • 58