Inverse Dictionary Lookup in Python

Reverse / invert a dictionary mapping

Python 3+:

inv_map = {v: k for k, v in my_map.items()}

Python 2:

inv_map = {v: k for k, v in my_map.iteritems()}

Python reverse dictionary lookup in list comprehension

In order to mimic the traditional loop, the outer loop should be over input_string and the inner loop should be over d in the list comprehension:

out = [k for i in input_string for k,v in d.items() if i==v]

Output:

[2, 1, 4]

Reverse lookup Dictionary

You can use dict.setdefault() with default list ([]) and then append the country in it:

out = {}
for country, (continent, _) in countries_dict.items():
out.setdefault(continent, []).append(country)

print(out)

Prints:

{'Europe': ['Andorra', 'Albania', 'Austria', 'Belgium'], 
'Asia': ['Afghanistan', 'Armenia', 'Azerbaijan', 'Bangladesh'],
'North America': ['Antigua and Barbuda', 'Barbados'],
'Africa': ['Angola'],
'South America': ['Argentina'],
'Oceania': ['Australia']}

How to reverse a dictionary (whose values are lists) in Python?

You can do it very simply like this:

newdict = {}
for key, value in olddict.items():
for string in value:
newdict.setdefault(string, []).append(key)

Python - Opposite of dictionary search

You can write simple lambda for this:

d={"a":5, "bf": 55, "asf": 55}

search_key = lambda in_d, val: (k for k,v in in_d.items() if v == val)

for k in search_key(d, 55):
print(k)

# since the lambda returns generator expression you can simply print
# the keys as follows:

print(list(search_key(d, 55)))
# or get the key list
key_list = list(search_key(d, 55))

Gives:

asf
bf

reverse mapping of dictionary with Python

If you do this often, you'll want to build a reverse dictionary:

>>> rev_ref = dict((v,k) for k,v in ref.iteritems())
>>> rev_ref
{'def': 'abc'}

>>> def revmapper(to):
... return rev_ref[to]

If it's rare, and you don't care if it's inefficient, do this:

>>> def revmapper(to):
... for k,v in ref.iteritems():
... if v == to: return k

Pythonic way to reverse search a nested dictionary

If you really want a one-liner you can go with the following:

next((k for k, v in DC.items() if v['ordertxid'] == MATCH), None)

How to reverse a dictionary in python and create a list out of the duplicate keys value

The most straightforward solution would be:

from collections import defaultdict

res = defaultdict(list)
for key, val in sorted(dic.items()):
res[val].append(key)

The same can be done with vanilla dictionary:

res = {}
for i, v in d_input.items():
res[v] = [i] if v not in res.keys() else res[v] + [i]

A neat solution using pandas:

import pandas as pd

pd.Series(dic).reset_index().groupby(0).agg(list).to_dict()['index']


Related Topics



Leave a reply



Submit