Reputation: 231
Good day ! I am having some trouble comparing values inside lists that are inside a dictionary.
{'lst_4':['New York', 'Amsterdam', 'Berlin'],'lst_5':['New York', 'Brussels',
Rome'],'lst_6':['Helsinki', 'Stockholm', Milan']}
The final goal is to compare the first item in each list, if they match I want to print which one it was. However I am having trouble comparing them because of the dict/listception.
My code so far:
x = 0
dct = {}
for row_cells in sheet.iter_rows(min_row=1, max_row=20):
x += 1
dct['lst_%s' %x] = []
for cell in row_cells:
if cell.value == None:
break
else:
dct['lst_%s' %x].append(cell.value)
print("-------------------------------------------------")
if not dct['lst_%s' %x]:
break
zin = dct['lst_%s' %x][0:]
print(zin)
Any help, or pointers are much appreciated.
Cheers,
Upvotes: 0
Views: 118
Reputation: 27283
I would use itertools.combinations
for this:
from itertools import combinations
for one, two in combinations(dct, 2):
if dct[one][0] == dct[two][0]:
print("Both", one, "and", two, "have", dct[one][0])
Upvotes: 2
Reputation: 31670
If your goal is to detect if every list has the same first element, just do:
my_dict = {'lst_4':['New York', 'Amsterdam', 'Berlin'],
'lst_5':['New York', 'Brussels', 'Rome'],
'lst_6':['Helsinki', 'Stockholm', 'Milan']}
keys = list(my_dict.keys())
if all([my_dict[k][0] == my_dict[keys[0]][0] for k in keys]):
print(my_dict[keys[0]][0])
In your example, there would be no output.
But if you want to find if 2 lists have the same first element, you could do something like:
my_dict = {'lst_4':['New York', 'Amsterdam', 'Berlin'],
'lst_5':['New York', 'Brussels', 'Rome'],
'lst_6':['Helsinki', 'Stockholm', 'Milan']}
keys = list(my_dict.keys())
for i, k1 in enumerate(keys):
for j, k2 in enumerate(keys[i+1:]):
if my_dict[k1][0] == my_dict[k2][0]:
print(my_dict[k1][0])
In your case, the output is:
"New York"
You iterate over the lists to find if a couple of lists have the same first element.
Upvotes: 2
Reputation: 2992
You could try this:
d = {'lst_4':['New York', 'Amsterdam', 'Berlin'],'lst_5':['New York', 'Brussels', 'Rome'],'lst_6':['Helsinki', 'Stockholm', 'Milan']}
def findDuplicateFirstItem(dictionary):
s = set()
for value in dictionary.values():
if value[0] not in s:
s.add(value[0])
else:
print(value[0])
findDuplicateFirstItem(d)
>>>New York
Upvotes: 1