简体   繁体   中英

Convert a nested dictionary into list of tuples

I have a dictionary -

d={'revenues':
             {
              '201907':
                      {'aaa.csv':'fdwe34x2'},
              '201906':{'ddd.csv':'e4c5q'}
             },    
   'complaints':
             {'2014':
                    {'sfdwa.csv','c2c2jh'}
             }
  }

I want to convert it into list of tuples -

[
 ('revenues','201907','aaa.csv','fdwe34x2'),
 ('revenues','201906','ddd.csv','e4c5q'),
 ('complaints','2014','sfdwa.csv','c2c2jh')
]

I tried using list comprehensions , but did not help -

l = [(k,[(p,q) for p,q in v.items()]) for k,v in d.items()]
print(l)
    [('revenues', [('201907', {'aaa.csv': 'fdwe34x2'}), ('201906', {'ddd.csv': 'e4c5q'})]),
     ('complaints', [('2014', {'c2c2jh', 'sfdwa.csv'})])]

Any suggestions?

If you're not sure how many levels this list may have, it seems that what you need is recursion:

def unnest(d, keys=[]):
    result = []
    for k, v in d.items():
        if isinstance(v, dict):
            result.extend(unnest(v, keys + [k]))
        else:
            result.append(tuple(keys + [k, v]))
    return result

Just a friendly reminder: before Python 3.6, dict order is not maintained.

[('complaints', '2014', 'sfdwa.csv', 'c2c2jh'),
 ('revenues', '201906', 'ddd.csv', 'e4c5q'),
 ('revenues', '201907', 'aaa.csv', 'fdwe34x2')]

您可以遍历字典的级别:

[(x, y, z) for x in d for y in d[x] for z in d[x][y]]

You can do it using a list comprehension, but it would be quite complex, and not easy to maintain if the structure changes. Unless you especially need good performance, I would suggest using a generic recursive function:

def unnest(d, keys=[]):
    result = []
    if isinstance(d, dict):
        for k, v in d.items():
            result.extend(unnest(v, keys + [k]))
    elif isinstance(d, list):
        result.append(tuple(keys + d))
    elif isinstance(d, set) or isinstance(d, tuple):
        result.append(tuple(keys + list(d)))
    else:
        result.append(tuple(keys + [d]))
    return result

As a bonus, I've also supported lists and tuples during the recursion, in addition to the set on the provided example.

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