Я довольно новичок в python и имею следующую проблему. У меня есть вложенный словарь в виде
dict = {'a': {'1','2'}, 'b':{'5','1'}, 'c':{'3','2'}}
и хотел бы найти все ключи с одинаковыми значениями. Вывод должен выглядеть примерно так.
1 : [a,b]
2 : [a,c]
..
Заранее большое спасибо за любую помощь!
dict = {'a': {'1','2'}, 'b':{'5','1'}, 'c':{'3','2'}}
output = {}
for key, value in dict.items():
for v in value:
if v in output.keys():
output[v].append(key)
else:
output[v] = [ key ]
print(output)
И выход будет
{'2': ['a', 'c'], '1': ['a', 'b'], '5': ['b'], '3': ['c']}
вы можете поменять ключ-значение в dict, создать словарь значения-ключа, если вам нужны только дублированные значения (find all the keys that have the same values
), вы можете filter
это:
from collections import defaultdict
def get_duplicates(dict1):
dict2 = defaultdict(list)
for k, v in dict1.items():
for c in v:
dict2[c].append(k)
# if you want to all values, just return dict2
# return dict2
return dict(filter(lambda x: len(x[1]) > 1, dict2.items()))
выход:
{'1': ['a', 'b'], '2': ['a', 'c']}
Вы можете использовать defaultdict
, чтобы легко построить вывод (и отсортировать его, если хотите, чтобы ключи были в отсортированном порядке):
from collections import defaultdict
d = {'a': {'1','2'}, 'b':{'5','1'}, 'c':{'3','2'}}
out = defaultdict(list)
for key, values in d.items():
for value in values:
out[value].append(key)
# for a sorted output (dicts are ordered since Python 3.7):
sorted_out = dict((k, out[k]) for k in sorted(out))
print(sorted_out)
#{'1': ['a', 'b'], '2': ['a', 'c'], '3': ['c'], '5': ['b']}
прежде чем мы перейдем к решению, позвольте мне сказать вам кое-что. У вас там не вложенный словарь, а скорее наборы в словаре.
Некоторые термины Python, чтобы прояснить это:
Массив: [ 1 , 2 ]
Arrays are enclosed in square braces & separated by commas.
Словарь: { "а": 1, "б": 2}
Dictionaries are enclosed in curly braces & separate "key":value pairs with comma. Here, "a" & "b" are keys & 1 & 2 would be their respective values.
Установить: { 1 , 2 }
Sets are enclosed in curly braces & separated by commas.
dict = {'a': {'1','2'}, 'b':{'5','1'}, 'c':{'3','2'}}
Здесь {'1', '2'} — это набор в словаре с ключом а. Таким образом, то, что у вас есть, фактически установлено в словаре, а не во вложенном словаре.
Переходя к решению, наборы не являются итерируемыми, то есть вы не можете проходить их один за другим. Итак, вы должны превратить их в списки, а затем повторить их.
# Initialize the dictionary to be processed
data = {'a': {'1','2'}, 'b':{'5','1'}, 'c':{'3','2'}}
# Create dictionary to store solution
sol = {} # dictionary to store element as a key & sets containing that element as an array
# Eg., sol = { "1" : [ "a" , "b" ] }
# This shows that the value 1 is present in the sets contained in keys a & b.
# Record all elements & list every set containing those elements
for key in data. keys (): # iterate all keys in the dictionary
l = list ( data [ key ] ) # convert set to list
for elem in l: # iterate every element in the list
if elem in sol. keys (): # check if elem already exists in solution as a key
sol [ elem ]. append ( key ) # record that key contains elem
else:
sol [ elem ] = [ key ] # create a new list with elem as key & store that key contains elem
# At this time, sol would be
# {
# "1" : [ "a" , "b" ] ,
# "2" : [ "a" , "C" ] ,
# "3" : [ "c" ] ,
# "5" : [ "b" ]
# }
# Since, you want only the ones that are present in more than 1 sets, let's remove them
for key in sol : # iterate all keys in sol
if sol [ key ]. length < 2 : # Only keys in at least 2 sets will be retained
del sol [ key ] # remove the unrequired element
# Now, you have your required output in sol
print ( sol )
# Prints:
# {
# "1" : [ "a" , "b" ] ,
# "2" : [ "a" , "c" ]
# }
Я надеюсь, что это поможет вам...
Это легко сделать с помощью defaultdict
из collections
,
>>> d = {'a': {'1','2'}, 'b':{'5','1'}, 'c':{'3','2'}}
>>> from collections import defaultdict
>>> dd = defaultdict(list)
>>> for key,vals in d.items():
... for val in vals:
... dd[val].append(key)
...
>>>>>> dict(dd)
{'1': ['a', 'b'], '3': ['c'], '2': ['a', 'c'], '5': ['b']}
Этого легко добиться с помощью двух внутренних циклов for:
dict = {'a': {'1','2'}, 'b':{'5','1'}, 'c':{'3','2'}}
out = {}
for key in dict:
for value in dict[key]:
if value not in out:
out[value]= [key]
else:
out[value]+= [key]
print out # {'1': ['a', 'b'], '3': ['c'], '2': ['a', 'c'], '5': ['b']}