'Python: Get key of the outer of two nested dicts based on one of the values in the inner dict in one line [duplicate]
How to get the desired result in python?
Base nested dictionary:
dictionary = {"aliceCo": {'name': "Cooper, Alice", 'group': 'finance'},
"bobDe": {'name': "Decker, Bob", 'group': 'hr'},
"caecilEl": {'name': "Elton, Caecil", 'group': 'sales'}
[many similar entrys...]
}
My attempt:
def get_result_list(dictionary, search_string):
return [[key for inner_val in val.values() if search_string in inner_val] for key, val in dictionary.items()]
my_result_list = get_result_list(dictionary, 'sales')
My result:
my_result_list = [[], [], ['caecilEl'], [], [], ...]
Desired result:
my_result_list = ['caecilEl']
I get that I have double lists from the return line, but I found no way to omit them. Also all the empty lists are not wanted. I could go over the result and fix it in another function, but I wish to do it in the inital function.
Thanks for any advice or hints on where to look for a solution!
Solution 1:[1]
In some cases, it is better to even use a for loop since it is easier to understand and read. I've tried both the solutions:
Using list comprehension:
dnames = {"aliceCo": {'name': "Cooper, Alice", 'group': 'finance'},
"bobDe": {'name': "Decker, Bob", 'group': 'hr'},
"caecilEl": {'name': "Elton, Caecil", 'group': 'sales'}
}
ans = [key for key,value in dnames.items() if value['group'] == 'sales']
ans
Using 2 for loop:
ans = []
for key,value in dnames.items():
for key1,value1 in value.items():
if value1 == 'sales':
ans.append(key)
Using 1 for loop:
ans = []
for key,value in dnames.items():
if value['group] == 'sales':
ans.append(key)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Prats |
