0

I have the necessity to check if a specific value correspond to the value of a multidimensional dict (specifying the key).

multi_dict = [
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
{'key1': 'value10', 'key2': 'value20', 'key3': 'value30'}
]

I'm coming from a PHP environment and I know that there's a function that does that: array_column There's something like this also for Python?

Possible output specifying key1 in order to check if a value correspond:

[value1, value10]
Keaire
  • 879
  • 1
  • 11
  • 30
  • Can you give your expected output? – iz_ Jan 27 '19 at 19:42
  • so you need all `key1` values across all dicts? – Patrick Artner Jan 27 '19 at 19:44
  • I added a possible output, but mainly I need to check if a static value correspond to the values of a multi dict specifying the key, so if I can return all the values of a specific key in a simple list I can do it easily. – Keaire Jan 27 '19 at 19:45

2 Answers2

2

You can use a list comprehension:

multi_dict = [
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
    {'key1': 'value10', 'key2': 'value20', 'key3': 'value30'}
]

result = [d['key1'] for d in multi_dict]
print(result)

Output:

['value1', 'value10']

If you wanted to emulate the third argument of array_column, the index key, you can use dictionary comprehension:

result = {d['key1']: d['key2'] for d in multi_dict}
print(result)

Output:

{'value1': 'value2', 'value10': 'value20'}
iz_
  • 15,923
  • 3
  • 25
  • 40
1

You can extract all values for a key of all dicts:

multi_dict = [ {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
               {'key1': 'value10', 'key2': 'value20', 'key3': 'value30'},
               {                   'key2': 'value30', 'key3': 'value40'},
             ]

val_key1 = [d.get('key1') for d in multi_dict] 

print(val_key1)  

Output:

['value1', 'value10', None]

You should use dict.get(key) to get a None in case a key is missing.

Doku:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69