Home > Software engineering >  python get dictionary key from value is list
python get dictionary key from value is list

Time:12-03

I have two dictionaries:

first_dict = {'a': ['1', '2', '3'],
              'b': ['4', '5'],
              'c': ['6'],
              }
second_dict = {'1': 'wqeewe',
               '2': 'efsafa',
               '4': 'fsasaf',
               '6': 'kgoeew',
               '7': 'fkowew'
               }

I want to have a third dict that will contain the key of second_dict and its corresponding value from first_dict's key. This way, I will have :

third_dict = {'1' : 'a',
              '2' : 'a',
              '4' : 'b',
              '6' : 'c',
              '7' : None,

}

here is my way:

def key_return(name):
  for key, value in first_dict.items():
    if name == value:
      return key
    if isinstance(value, list) and name in value:
      return key
  return None

reference: Python return key from value, but its a list in the dictionary

However, I wondering that the another way using dict.get() or something else. Any help would be appreciated. Thanks.

CodePudding user response:

you can do it like that:

Code

first_dict = {'a': ['1', '2', '3'],
              'b': ['4', '5'],
              'c': ['6'],
              }

second_dict = {'1': 'wqeewe',
               '2': 'efsafa',
               '4': 'fsasaf',
               '6': 'kgoeew',
               '7': 'fkowew'
               }

third_dict = dict()

for second_key in second_dict.keys():
    found = False
    for first_key, value in first_dict.items():
        if second_key in value:
            third_dict.setdefault(second_key, first_key )
            found = True
    if not found:
        third_dict.setdefault(second_key, None)
                    
print(third_dict)

Output:

{'1': 'a', '2': 'a', '4': 'b', '6': 'c', '7': None}

Hope this helps

CodePudding user response:

version with a_dict.get()

third_dict = {i: {i:k for k,v in first_dict.items() for i in v}.get(i) for i in second_dict.keys()}

this part {i:k for k,v in first_dict.items() for i in v}
creates a dict like {'1': 'a', '2': 'a', '3': 'a', '4': 'b', '5': 'b', '6': 'c'}

CodePudding user response:

You can map the values in the first dictionary to their keys with:

values_map = dict([a for k, v in first_dict.items() for a in zip(v, k*len(v))])

then use this map to create the third dictionary:

third_dict = {key: values_map.get(key) for key, value in second_dict.items()}

Since I get that the first_dict may contain single values instead of list you may want first to convert those values to list with:

first_dict = dict(map(lambda x: (x[0], x[1]) if isinstance(x[1], list) else (x[0], [str(x[1])]), first_dict.items()))

CodePudding user response:

res = {
    x: k
    for k, xs in first_dict.items()
    for x in xs
    if x in second_dict
}

this creates 1:a , 2:a, 4:b etc. If you also want missing keys like 7:None join it with a dummy dict:

res = {k: None for k in second_dict} | {
    x: k
    for k, xs in first_dict.items()
    for x in xs
    if x in second_dict
}
  • Related