简体   繁体   中英

Convert nested lists to dictionary in python

I need to convert the nested list result = [[450, 455, 458], [452, 454, 456, 457], [451, 453]] to a dictionary like:

{
    0: 
         {
             450: None,
             455: 450,
             458: 450
         },
    1:   {
             452: None,
             454: 452,
             456: 452,
             457: 452
         },
    2:   {
             451: None,
             453: 451
         }

}

Please take a look at this and assist:

result_group = {}
for sub_group in result:
    group_count = 0
    first_rel_item = 0
    result_group[group_count] = dict()
    for item in sub_group:
        if item == sub_group[0]:
            result_group[group_count][item] = None
            first_rel_item = item
            continue
        result_group[group_count]['item'] = first_rel_face
        group_count += 1

I messed up with this as i get key Error:1 cant add to dictionary.

This is one way:

lst = [[450, 455, 458], [452, 454, 457], [451, 453]]

res = {i: {w: None if w == v[0] else v[0] for w in v}
          for i, v in enumerate(lst)}

Result

{0: {450: None, 455: 450, 458: 450},
 1: {452: None, 454: 452, 457: 452},
 2: {451: None, 453: 451}}

Explanation

  • Use ternary statement to determine whether you choose None or v[0] .
  • Use enumerate to extract index of nested list.

Try this:

result_group = {}
group_count = 0
for sub_group in result:
    first_rel_item = 0
    result_group[group_count] = {}
    result_group[group_count][sub_group[0]] = None
    previtem = sub_group[0]
    for item in sub_group[1:]:
        result_group[group_count][item] = previtem
    group_count += 1

You could use a list comprehension here:

>>> result = [[450, 455, 458], [452, 454, 457], [451, 453]]

>>> dict(enumerate({**{i: a[0] for i in a[1:]}, **{a[0]: None}}
                   for a in result))

{0: {450: None, 455: 450, 458: 450},
 1: {452: None, 454: 452, 457: 452},
 2: {451: None, 453: 451}}

Note: this uses "extended" iterable unpacking, which was introduced in Python 3.5. z = {**x, **y} merges dictionaries x and y .

Each a is a sublist of result . You want to use a[0] as the value for the 1st elements and above, and None for the 0th element.

The assumption here is that you only want the 0th element of the sublist to have a corresponding None value. (If the 0th element were repeated, somewhere, it would use the 0th element as its value, as in @jpp's answer.)

# the nice solutions were already given, so by foot:

d = {}
result = [[450, 455, 458], [452, 454, 457], [451, 453]]

for idx,l in enumerate(result): # returns the index and the sublists data
    rMin = min(l)
    d[idx] = {}  # create a inner dict at key idx
    for i in l:
        d[idx][i] = None if i == rMin else rMin   # fill inner dicts keys

print(d)

Output:

{0: {450: None, 455: 450, 458: 450},
 1: {452: None, 454: 452, 457: 452},
 2: {451: None, 453: 451}}

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