Zaman Azam
Zaman Azam

Reputation: 39

searching value of list in dict and add it to new dictionary

I have one list and dictionary.i want to check if the element of list present in the dictionary then add it to the new dictionary

list1 = [name, number, ...]
mydict = {
    'house no': 12232,
    'stre11': 123,
    'name': ali,
    'area': new,
    'number': 032544,
    ...
}
newdict = {}

output:

newdict = {'name': ali, 'number': 032544}

Upvotes: 0

Views: 39

Answers (3)

Mark
Mark

Reputation: 92440

This is perfect opportunity to use a dictionary comprehension. For each key in list1, look up the value in mydict:

list1 = ['name','number']

mydict = {'house no': 12232, 'stre11': 123, 'name': 'ali', 'area': 'new', 'number': '032544'}

newdict = {k:mydict[k] for k in list1 }
# {'name': 'ali', 'number': '032544'}

Be warned that this will raise an exception if the key is not in mydict. If that's a possibility, you can add a condition:

{k:mydict[k] for k in list1 if k in mydict }

Upvotes: 3

Gabriel Milan
Gabriel Milan

Reputation: 723

A very simple and comprehensible way of doing this:

list1 = ['name', 'number']
mydict={'house no':12232,'stre11':123,'name':'ali','area':'new','number':32544}
newdict = {}

for entry in list1:
  if entry in mydict:
     newdict[entry] = mydict[entry]

Upvotes: 1

Aleksander Ikleiw
Aleksander Ikleiw

Reputation: 2685

We will iterate using items() function in mydict. If the value of any Key from it will be equal to any value from the desired_keyword the new_dict will have created a new key with that value.

mydict={'house no':12232,'stre11':123,'name':1,'area':2,'number': 1}
desired_keyword = [1, 4]
new_dic = {}
for i, j in mydict.items():
    for d in desire_keyword:
        if d == j:
            new_dic[i] = j

Upvotes: 0

Related Questions