How to reverse a dictionary that has repeated values
Using collections.defaultdict
:
from collections import defaultdict
reversed_dict = defaultdict(list)
for key, value in mydict.items():
reversed_dict[value].append(key)
How to reverse a dictionary with repeated values as a set
just create a new dictionary
newdict = {}
for key, val in d.items():
if val not in newdict:
newdict[val] = key
else:
newdict[val] = set((*newdict[val], key))
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']
how to invert a dictionary with multiple same values?
You are losing values because the values of the original dict (which can have duplicates) becomes keys in this one. You could do something like
inverted = defaultdict(list)
for key, value in original_dict.items():
inverted[value].append(key)
How to create a reverse dictionary that takes in account repeated values?
You have to iterate over the values in the list as well:
def reversed_dict(d):
new_dict = {}
for keys,values in d.items():
for val in values:
new_dict.setdefault(val, []).append(keys)
return new_dict
Removing inverse duplicates in dictionary python
You can turn each entry to a tuple
and use a set
to get O(n)
time.
d = {'a': ['b'],
'c': ['d'],
'x': ['y'],
'y': ['x'],
'i': ['j','k'],
'j': ['i','k'],
'k': ['i','j']}
seen = set()
to_remove = []
for key, val in d.items():
entry = tuple(sorted(val.copy() + [key]))
to_remove.append(key) if entry in seen else seen.add(entry)
for key in to_remove:
del d[key]
print(d)
Output:{'a': ['b'], 'c': ['d'], 'x': ['y'], 'i': ['j', 'k']}
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()}
How to remove duplicated keys in reverse order from dictionary (python)
You could do something along the following lines:
d = {('cat', 'tiger'): 18,
('tiger', 'cat'): 18,
('chines', 'gentleman'): 7,
('gentleman', 'chines'): 7}
result = {tuple(sorted(x)): y for x, y in d.items()}
# {('cat', 'tiger'): 18, ('chines', 'gentleman'): 7}
In this dict
comprehension, the last encountered value for each set of "equal" keys wins. With your sample data, this shouldn't matter because those keys have equla values. Note that this also just sorts the tuples, regardless of the sorted version actually occuring in the original dict
.
Related Topics
A Good Way to Make Long Strings Wrap to Newline
Elif' in List Comprehension Conditionals
How to Fix Selenium Webdriverexception: the Browser Appears to Have Exited Before We Could Connect
How to Read Class Attributes in the Same Order as Declared
Pandas Groupby and Sum Only One Column
Pandas: Subindexing Dataframes: Copies VS Views
Change Tick Frequency on X (Time, Not Number) Frequency in Matplotlib
How to Make a Local Variable (Inside a Function) Global
In What Order Does Python Display Dictionary Keys
Numpy 1.21.2 May Not Yet Support Python 3.10
Overriding the Save Method in Django Modelform
Python - Requests.Exceptions.Sslerror - Dh Key Too Small
Importing Class from Another File
What Do Backticks Mean to the Python Interpreter? Example: 'Num'
Rename Multiindex Columns in Pandas
Wrapping Long Y Labels in Matplotlib Tight Layout Using Setp