Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

Create a new dictionary from 2 existing dictionory (1 nested dictionory , 1 dictionory of lists) python

I have two dictionaries K and L. K is a Dictionary of lists and L is a nested dictionary

 K={
    'k1':[1,3,2],
    'k2':[3,4,5],
    'k3':[9,10,11]
    }

L = {
'l1':{'a':'1','b':'1','c':'2'},
'l2':{'a':'1','b':'3','c':'2'},
'l3':{'a':'1','b':'2','c':'2'},
'l4':{'a':'1','b':'4','c':'2'}
}

What I need: I want to create a new dictionary of lists based on the below condition.

  1. I need to check if b values of L are present in the K dictionary of the list or not.
  2. If present I need to return a new dictionary with Key of K dictionary and Key of L dictionary.

For the above example, I need to return something like this

M = {'k1':[l1,l3,l2]
     'k2':[l2,l4]
     }

Here is the code that I have tried:

M= {}
for k, v in K.items():
  temp = []
  for i in v:
    if L[i]['b'] in K[k]:
      temp.append(i)
      M[k] = temp
    
print(M)
question from:https://stackoverflow.com/questions/66068150/create-a-new-dictionary-from-2-existing-dictionory-1-nested-dictionory-1-dict

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You were looking up the wrong thing in L here L[I]. I would do this by creating a lookup intially from L, that way you don't have to loop through L for every key in K. From there you can go through K once, looking up the items from the lookup.

Using defaultdict also allows you to handle the case where L has b values that are the same

from collections import defaultdict

b_val_to_l = defaultdict(set)
for lkey, ldict in L.items():
    # For each ldict, extract the 'b' value, convert to an int and add the
    # l key to the set of l values for the corresponding b value
    b_val_to_l[int(ldict['b'])].add(lkey)

print(b_val_to_l)

M = defaultdict(list)
for k, v in K.items():
  for i in v:
      # For each value in the k, get the set of corresponding l values
      b_set = b_val_to_l.get(i, set())

      # Add to the output dict
      M[k].extend(list(b_set))

print(M)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...