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
Imread Returns None, Violating Assertion !_Src.Empty() in Function 'Cvtcolor' Error
Pandas Cannot Open an Excel (.Xlsx) File
How to Overload Python Assignment
How to Check If a Python Module Exists Without Importing It
Scraping Dynamic Content Using Python-Scrapy
Extract Images from PDF Without Resampling, in Python
What Does 'Valueerror: Cannot Reindex from a Duplicate Axis' Mean
Dynamically Add Field to a Form
Pylint "Unable to Import" Error - How to Set Pythonpath
How to Decrypt Openssl Aes-Encrypted Files in Python
How to Pass a Method as a Parameter in Python
Object of Custom Type as Dictionary Key
Automatically Import Modules When Entering the Python or Ipython Interpreter