-2

Let's say we have a dict

dict = {
  "a": "x",
  "b": "x",
  "c": "x",
  "d": "y",
  "e": "y",
  "f": "y",
}

How do I quickly check, if a set of specific keys all have the same value?

E.g.:

list_of_keys = ["a", "b", "c"]

should return True.

list_of_keys = ["b", "c", "d"]

should return False.

Thanks in advance.

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
Ipsider
  • 553
  • 1
  • 7
  • 20

5 Answers5

2

You can use built-in all function and compare all values to the first one:

all(dict[k] == dict[list_of_keys[0]] for k in list_of_keys)

Another suggestion (from the comments):

len(set(dict[k] for k in list_of_keys)) == 1

Sidenote: don't use dict as a variable name. It's python's built-in.

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
2

Using operator.itemgetter and a set:

from operator import itemgetter

len(set(itemgetter(*list_of_keys1)(dic))) == 1
# True

len(set(itemgetter(*list_of_keys2)(dic))) == 1
# False

Or, looping over the keys:

len(set(dic[k] for k in list_of_keys1)) == 1
# True

len(set(dic[k] for k in list_of_keys2)) == 1
# False

Used input:

dic = {
  "a": "x",
  "b": "x",
  "c": "x",
  "d": "y",
  "e": "y",
  "f": "y",
}

list_of_keys1 = ["a", "b", "c"]
list_of_keys2 = ["b", "c", "d"]
mozway
  • 194,879
  • 13
  • 39
  • 75
1

Maybe something iterative like this:

def check_if_all_same_value(keys, my_dict):
  value = my_dict[keys[0]]
  for key in keys:
    if my_dict[key] != value:
      return False
  return True

This will at first set the reference value to be the one of the first given key. The script will then iterate on the value of each key and, if it is not the same as the reference one, return False. If it finishes looping (e.g. if all keys have the same values), the function returns True.

1

Using iterools recipy (as suggested here) and "list comprehension"

from itertools import groupby

def all_equal(iterable):
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

my_dict = {
  "a": "x",
  "b": "x",
  "c": "x",
  "d": "y",
  "e": "y",
  "f": "y",
}
list_of_keys = ["a", "b", "c"]

ret = all_equal(my_dict[key] for key in list_of_keys)
print(ret)
Tzane
  • 2,752
  • 1
  • 10
  • 21
1

Quick test using all:

head, *tail = list_of_keys

all(dct[t] == dct[head] for t in tail)
user2390182
  • 72,016
  • 6
  • 67
  • 89