I have a dict:
my_dict = {
'train_1': ['a', 'b','c'],
'train_2': ['a', 'b', 'c', 'd'],
'train_3': ['a', 'b', 'c', 'd'],
'train_4': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
'train_5': ['a', 'b', 'c', 'd', 'e', 'f'],
'train_6': ['a', 'b', 'c', 'd']
}
I need to find all keys in the dict that have identical lists.
The output should be:
{
'group_1': ['train1'],
'group_2': ['train_2', 'train_3', 'train_6'],
'group_3': ['train_4'],
'group_4': ['train_5'],
}
I can use something like this for the task when the values in the dict are not lists:
flipped = {}
for key, value in my_dict.items():
print(value)
if value not in flipped:
flipped[value] = [key]
else:
flipped[value].append(key)
But how can I achieve this when the values are lists ?
Continuing from the comments, you could change the lists to tuple and then use them as the keys:
my_dict = {
'train_1': ['a', 'b','c'],
'train_2': ['a', 'b', 'c', 'd'],
'train_3': ['a', 'b', 'c', 'd'],
'train_4': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
'train_5': ['a', 'b', 'c', 'd', 'e', 'f'],
'train_6': ['a', 'b', 'c', 'd']
}
flipped = {}
for key, value in my_dict.items():
if tuple(value) not in flipped:
flipped[tuple(value)] = [key]
else:
flipped[tuple(value)].append(key)
print(flipped)
OUTPUT:
{('a', 'b', 'c'): ['train_1'], ('a', 'b', 'c', 'd'): ['train_3', 'train_6', 'train_2'], ('a', 'b', 'c', 'd', 'e', 'f'): ['train_5'], ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
: ['train_4']}
EDIT :
once, filtered. you could iterate over the new dict and assign the desired keys:
grouped_dct = {}
i = 1
for k,v in flipped.items():
grouped_dct['group_' + str(i)] = v
i += 1
print(grouped_dct)
OUTPUT:
{'group_1': ['train_4'], 'group_2': ['train_5'], 'group_3': ['train_2', 'train_6', 'train_3'], 'group_4': ['train_1']}
if order of element in the list matters then below should work for you.
flipped = {}
for key, value in my_dict.items():
print(value)
newVal = ''.join(x for x in value)
if newVal not in flipped:
flipped[newVal] = [key]
else:
flipped[newVal].append(key)
print(flipped)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.