简体   繁体   English

在 Python 中展平字典列表

[英]Flattening a list of dictionaries in Python

I have a list of dictionaries with the following shape:我有一个具有以下形状的字典列表:

x = [{'website_ctr': [{'action_type': 'link_click', 'value': '0.481928'}],
  'campaign_id': 'x',
  'date_start': '2021-11-01',
  'date_stop': '2021-11-01',
  'account_id': 'y'},
 {'website_ctr': [{'action_type': 'link_click', 'value': '0.40568'}],
  'campaign_id': 'x',
  'date_start': '2021-11-01',
  'date_stop': '2021-11-01',
  'account_id': 'y'},
 {'website_ctr': [{'action_type': 'link_click', 'value': '0.711382'}],
  'campaign_id': 'x',
  'date_start': '2021-11-01',
  'date_stop': '2021-11-01',
  'account_id': 'y'}]

I'm trying flatten the dictionary, so that each object in the list looks something like this我正在尝试压平字典,以便列表中的每个对象看起来像这样

{'website_ctr-0-action_type': 'link_click',
 'website_ctr-0-value': '0.481928',
 'campaign_id': 'x',
 'date_start': '2021-11-01',
 'date_stop': '2021-11-01',
 'account_id': 'y'}

I've found the following codesnippet, and tried to adapt it to my case, however I keep getting an AttributeError: 'str' object has no attribute 'items' error, which I assume comes from my first loop for dictionary in datalist .我找到了以下代码片段,并尝试将其调整为适合我的情况,但是我不断收到AttributeError: 'str' object has no attribute 'items'错误,我认为这来自我for dictionary in datalist第一个for dictionary in datalist循环。

import collections

def flatten(datalist, parent_key=False, separator='-'):   
    items = []
    for dictionary in datalist:
        for key, value in dictionary.items():
            new_key = str(parent_key) + separator + key if parent_key else key
            if isinstance(value, collections.MutableMapping):
                items.extend(flatten(value, new_key, separator).items())
            elif isinstance(value, list):
                for k, v in enumerate(value):
                    items.extend(flatten({str(k): v}, new_key).items())
            else:
                items.append((new_key, value))
    return dict(items)

Question: What am I doing wrong?问题:我做错了什么?

Full Traceback:完整追溯:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
c:\Users\avk\facebookdata\ReadData\fb_credentials.py in <module>
----> 1 flatten(x)

c:\Users\avk\facebookdata\ReadData\fb_credentials.py in flatten(datalist, parent_key, separator)
    102             elif isinstance(value, list):
    103                 for k, v in enumerate(value):
--> 104                     items.extend(flatten({str(k): v}, new_key).items())
    105             else:
    106                 items.append((new_key, value))

c:\Users\avk\facebookdata\ReadData\fb_credentials.py in flatten(datalist, parent_key, separator)
     96     items = []
     97     for dictionary in datalist:
---> 98         for key, value in dictionary.items():
     99             new_key = str(parent_key) + separator + key if parent_key else key
    100             if isinstance(value, collections.MutableMapping):

AttributeError: 'str' object has no attribute 'items'

You can flatten it like:您可以将其展平,例如:

def flatten(obj, pre="", sep="-"):
    if isinstance(obj, dict):
        items = obj.items()
    elif isinstance(obj, (list, tuple)):
        items = enumerate(obj)
    else:
        return {pre: obj}
    result = {}
    for k, v in items:
        result.update(flatten(v, f"{pre}{sep}{k}".strip(sep), sep))
    return result

flatten(x[0])
# {'account_id': 'y',
#  'campaign_id': 'x',
#  'date_start': '2021-11-01',
#  'date_stop': '2021-11-01',
#  'website_ctr-0-action_type': 'link_click',
#  'website_ctr-0-value': '0.481928'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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