Home > OS >  Python Dictionary remove pairs when key not matching reference list
Python Dictionary remove pairs when key not matching reference list

Time:12-03

This is what I have:

names = ['Bob', 'Mike', 'Nia', 'Tim', 'Holly', 'Liam', 'Dave']
temperatures = ['-0.3', '-0.6', '-0.8', '-0.2', '-1.3', '-2.1', '-0.4']

main_dictionary = {'Bob' : '-0.3', 'Mike': '-0.6', 'Nia' : '-0.8', 'Tim':'-0.2', 'Holly':'-1.3', 'Liam':'-2.1', 'Dave':'-0.4'}

I'm trying to produce a dictionary by comparing it to the list of selected_names against the main_dictionary to produce the updated_dictionary

selected_names = ['Nia', 'Holly', 'Liam', 'Dave']

updated_dictionary = {'Nia' : '-0.8',  'Holly':'-1.3', 'Liam':'-2.1', 'Dave':'-0.4'}

So far in my project Ive compared many lists using .intersection but can seem to work out how to apply it to a dictionary.

CodePudding user response:

Probably a simple dict comprehension is enough:

updated_dictionary = {x: main_dictionary[x] for x in selected}

If selected may contain invalid keys, you could explicitely ignore them:

updated_dictionary = {x: main_dictionary[x] for x in selected if x in main_dictionary[x]}

See also Create a dictionary with list comprehension and Filter dict to contain only certain keys?

CodePudding user response:

Try this

main_dictionary = {'Bob' : '-0.3', 'Mike': '-0.6', 'Nia' : '-0.8', 'Tim':'-0.2', 'Holly':'-1.3', 'Liam':'-2.1', 'Dave':'-0.4'}
selected_names = ['Nia', 'Holly', 'Liam', 'Dave']

newd = {k:v for k,v in main_dictionary.items() if k in selected_names}

print(newd)

CodePudding user response:

Try this:

names = ['Bob', 'Mike', 'Nia', 'Tim', 'Holly', 'Liam', 'Dave']
temperatures = ['-0.3', '-0.6', '-0.8', '-0.2', '-1.3', '-2.1', '-0.4']

main_dictionary = {
    'Bob': '-0.3',
    'Mike': '-0.6',
    'Nia': '-0.8',
    'Tim': '-0.2',
    'Holly': '-1.3',
    'Liam': '-2.1',
    'Dave': '-0.4'
}

selected_names = ['Nia', 'Holly', 'Liam', 'Dave']
output = {
    'Nia': '-0.8',
    'Holly': '-1.3',
    'Liam': '-2.1',
    'Dave': '-0.4'
}
updated_dictionary = {k: v for k, v in main_dictionary.items() if k in selected_names}

if __name__ == '__main__':
    print("main", main_dictionary)
    print("updated", updated_dictionary)
    print(updated_dictionary == output)

# It produces:
# {'Nia': '-0.8', 'Holly': '-1.3', 'Liam': '-2.1', 'Dave': '-0.4'}
# updated {'Nia': '-0.8', 'Holly': '-1.3', 'Liam': '-2.1', 'Dave': '-0.4'}
# True
  • Related