0

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!

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
CB Mantra
  • 3
  • 1
  • Welcome to Stack Overflow. The linked duplicate should answer your question. You should also read [ask] and note that, since this is *not a discussion forum*, questions [should not include](https://meta.stackoverflow.com/questions/260776/should-i-remove-fluff-when-editing-questions/) language thanking people (unnecessary and a distraction for people who search later), or saying that any help or hints are desired ([not specific enough](https://meta.stackoverflow.com/questions/284236)). – Karl Knechtel Feb 01 '22 at 18:25
  • Finally, here is [a great resource for list comprehension questions](https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/). – Karl Knechtel Feb 01 '22 at 18:25

2 Answers2

0

The empty lists are included because of the nested list.

This function would give the desired result.

def get_result_list(dictionary, search_string):
    return [key for key, val in dictionary.items() if search_string in val.values()]
kaliappan
  • 16
  • 2
0

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)
Prats
  • 649
  • 2
  • 15