Szymon
Szymon

Reputation: 633

How to keep order after extracting a subset of a dictionary?

I want to make a dictionary (or list) that is a subset of another dictionary. Please look at my code below:

ThePythons = {
    'GC': 'Graham Chapman',
    'JC': 'John Cleese',
    'EI': 'Eric Idle',
    'MP': 'Michael Palin'
}

query = ['EI', 'JC']

output = {key: value for key, value in ThePythons.items() if key in query}
print(output)

Sometimes the output is:

{'JC': 'John Cleese', 'EI': 'Eric Idle'}

and sometimes is:

{'EI': 'Eric Idle', 'JC': 'John Cleese'}

How to keep (save) the output in exactly the same order as query is? I want the output always as:

{'EI': 'Eric Idle', 'JC': 'John Cleese'}

The output can also be a list type (<class 'list'>). For example:

[['EI', 'Eric Idle'], ['JC', 'John Cleese']]

Upvotes: 1

Views: 133

Answers (3)

hintze
hintze

Reputation: 630

Since Python 3.7+, your code keeps order:

ThePythons = {
    'GC': 'Graham Chapman',
    'JC': 'John Cleese',
    'EI': 'Eric Idle',
    'MP': 'Michael Palin'
}

query = ['EI', 'JC']

output = {key: value for key, value in ThePythons.items() if key in query}
print(output)

always returns

{'EI': 'Eric Idle', 'JC': 'John Cleese'}

Upvotes: 0

venpa
venpa

Reputation: 4318

You can iterate over list and get item from dictionary using list comprehension:

output = [[item,ThePythons[item]] for item in query if item in ThePythons]
print output

output:

[['EI', 'Eric Idle'], ['JC', 'John Cleese']]

Using map:

map(lambda x: [x,ThePythons[x]] if x in ThePythons else [x,"Not found"], query)

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601559

Dictionaries are unordered. You have to use a list comprehension instead of a dictionary comprehension to keep the order:

output = [(key, ThePythons[key]) for key in query]

Upvotes: 2

Related Questions