Mixalis
Mixalis

Reputation: 542

Creating a dictionary from a dictionary using a tuple Python

given a dictionary with N keys and a tuple of K keys, K<=N is there a pythonic way to get a dictionary with only the K keys?

ex.

orig_dict = {'key1':'value1', 'key2':'value2', ..., 'keyN':'valueN'}

tuple = ('key2', 'keyM')

newdict = myFunc(orig_dict, tuple)

print newdict

Output:

'key2':'value2', 'keyM':'valueM'

Upvotes: 1

Views: 176

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

Just use a comprehension:

tple = ('key2', 'keyM')
{k: orig_dict[k] for k in tple}

Or if you prefer functional:

from operator import itemgetter

dict(zip(tple, itemgetter(*tple)(orig_dict)))

What is more pythonic is debatable, what is definitely not pythonic is using tuple as a variable name.

If some keys may not exist you can get the intersection with viewkeys:

dict(zip(tuple, itemgetter(*orig_dict.viewkeys() & tple)(orig_dict)))

{k : orig_dict[k] for k in orig_dict.viewkeys() & tple}

For python3 just use .keys() which returns a dict_view object as opposed to a list in python2.

If you wanted to give a default value of None for missing keys, you could also use map with dict.get so missing keys would have their value set to None.

dict(zip(tuple, map(orig_dict.get, tuple)

Upvotes: 2

mhawke
mhawke

Reputation: 87064

Use a dictionary comprehension

orig_dict = {'key1':'value1', 'key2':'value2', 'keyN':'valueN'}
keys = ('key2', 'keyM')

>>> {k:orig_dict[k] for k in keys if k in orig_dict}
{'key2': 'value2'}

This will be more efficient than iterating over the dictionary's keys and checking whether the key exists in the tuple because it is an O(1) operation to lookup a dict vs O(n) to search in a tuple.

Alternatively you can use a set to get the common keys and combine that with a dict comprehension:

>>> {k:orig_dict[k] for k in set(keys).intersection(orig_dict)}
{'key2': 'value2'}

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95917

You can use a dictionary comprehension:

{k:v for k,v in orig_dict.iteritems() if k in tuple_keys}

Observe:

>>> orig_dict = {'key1':'value1', 'key2':'value2', 'keyN':'valueN'}
>>> tuple_keys = ('key2', 'keyN')
>>> {k:v for k,v in orig_dict.iteritems() if k in tuple_keys}
{'keyN': 'valueN', 'key2': 'value2'}

Upvotes: 2

Related Questions