简体   繁体   中英

List of Dictionaries to a lists of correlated dictionaries

I have this list:

list = [ { 1: [3], 2: [6] }, { 3: [4,5], 6: [8] }, { 4: [7], 5: [7] } ]

It is representing the whole correlation between object IDs for all the objects I have.

What I want to extract from this list:

l1 = [ { 1: [3] }, { 3: [4,5] }, { 4: [7], 5: [7] } ]

l2 = [ { 2: [6] }, { 6: [8] } ]

Let me give some explanation!

For clarity, please find the image bellow:

在此处输入图片说明

So, as you can see, each object is represented by its ID. To form "list", I start from the IDs of the peripheral objects on the left, such IDs will be the keys of the first dictionary (of "list"), the values of these keys are the IDs of the objects connected on the right (we are putting the value(s) in a list). These values, will be the keys of the second dictionary (don't repeat the keys if you have repeated values from the previous dictionary, just right it once), and repeat such steps until reaching last IDs.

These objects are forming pattern(s) according to the relation between their IDs. In the problem, I will be given the number of patterns they are forming. In the picture I gave the link to, they are forming two patterns.

Pattern: is the group of objects having IDs correlated to each other in a certain way

Its worked for me:

my_dict = [ { 1: [3], 2: [6] }, { 3: [4,5], 6: [8] }, { 4: [7], 5: [7] } ]
new_dict = []

# read
def read(n, p, dictionary):
  a = list(dictionary[n])[p]
  if len(new_dict)<=p:
    new_dict.append([])
  new_dict[p].append({a : dictionary[n][a]})
  bucle(dictionary[n][a], n+1, p, dictionary)
def bucle(key, n, p, dictionary):
  try:
    for keys in key:
      new_dict[p].append({keys: dictionary[n][keys]})
      bucle(dictionary[n][keys], n+1, p, dictionary)
  except:
    pass
read(0, 0, my_dict)
read(0, 1, my_dict)
print(new_dict)

result:

new_dict = [[{1: [3]}, {3: [4, 5]}, {4: [7]}, {5: [7]}], [{2: [6]}, {6: [8]}]]
new_dict[0] = [{1: [3]}, {3: [4, 5]}, {4: [7]}, {5: [7]}]
new_dict[1] = [{2: [6]}, {6: [8]}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM