Home > Blockchain >  Is there a way to use values in a list to search a dictionary?
Is there a way to use values in a list to search a dictionary?

Time:05-06

I have a list of list that has values which are the same as some keys in a dictionary, like so:

list_a = [["a", "c", "e"], ["b", "f", "g"], ["b", "d", "i"]]
dict_a = {"a": "3", "b": "3", "c": "2", "d": "5", "e": "4", "f": "3", "g": "3", "h": "1", "i": "1"}

I want to use the values in list_a to access dict_a and check if the values by those keys are the same. To make myself clear: I take the first list in list_a and use those values to check if values in dict_a by keys "a", "c" and "e" share the same value. If yes (so if those three keys share the same values) do something, if not keep looking. So far I have tried different variations of this:

for i in range(len(list_a)):
check = list_a[i]
  for j in range(len(check)):
      if dict_a[check[j]] == "3":
        #do stuff

With no result other than doing the thing every time it find a correspondence. What am I missing?

CodePudding user response:

Use the all() function to check if all the values are the same.

And use any() to test if this is true for any of the sublists in list_a.

if any((all(dict_a.get(v) == dict_a.get(check[0]) for v in check) for check in list_a):
    # do stuff

CodePudding user response:

If you only need the first matching result you can get it in one line of code:

list_a = [['a', 'c', 'e'], ['b', 'f', 'g'], ['b', 'd', 'i']]
dict_a = {'a': '3', 'b': '3', 'c': '2', 'd': '5', 'e': '4', 'f': '3', 'g': '3', 'h': '1',
          '1': '1'}
if (result := next((sublist for sublist in list_a if len(set(dict_a.get(v, v) for v in sublist)) == 1), None)):
    # do stuff
    print(result)

The basic idea is to loop over all inner lists. Then we take each element of the inner list, get the corresponding value from the dictionary and build a set with all those values. If this set has only one element then all the values are the same. We return the element with next and provide a default value of None if no matching inner list could be found.


After your clarification that all those values must match a given value there is a different solution:

value_to_find = '3'
for sublist in list_a:
    if all(dict_a.get(value, value) == value_to_find for value in sublist):
        print(sublist)
        # your code here
        break

Remove the break if you want to perform the action on multiple inner lists if multiple inner lists match.

CodePudding user response:

list_a = [["a", "c", "e"], ["b", "f", "g"], ["b", "d", "i"]]
dict_a = {"a": "3", "b": "3", "c": "2", "d": "5", "e": "4", "f": "3", "g": "3", "h": "1", "i": "1"}
for i in range(len(list_a)):
    check = list_a[i]
    lst = [dict_a[check[j]] for j in range(len(check))]
    if lst[:-1] == lst[1:]:
        print("All same")
    else:
        print("Not All same")
  • Related