Home > Enterprise >  how to add keys from an existing dictionary to a new dictionary
how to add keys from an existing dictionary to a new dictionary

Time:11-28

I have a dictionary that looks like this:

pris = {'äpplen': [12,13,15,16,17], 'bananer': [14,17,18,19], 'citroner': [20,13,14,15,16], 'hallon': [23,34,45,46,57], 'kokos': [12,45,67,89]}

an another:

t={'äpplen', 'bananer', 'hallon'} 

What I'm trying to do is to create a new dictionary with only the elements in t.

New_dictionary= {'äpplen': [12,13,15,16,17], 'bananer': [14,17,18,19], 'hallon': [23,34,45,46,57]}

So far, I've done this: I tried to remove the not desired keys in dictionary pris, but I get all the elements that I don't want. I tried with append, etc, but it doesn't work.

for e in t: 
    if e is not pris:
        del pris[e]
print(pris)
>>> {'citroner': [20, 13, 14, 15, 16], 'kokos': [12, 45, 67, 89]}

Can someone help me?

CodePudding user response:

try this:

new_d = dict()
for key in t:
    if key in pris:
        new_d[key] = pris[key]

here is how in 1 line

new_d = {key:pris[key] for key in t if key in pris}

CodePudding user response:

New_dictionary={k:pris[k] for k in t}

  • Related