试图将字典中的列表展平为关键值

时间:2018-03-02 14:57:02

标签: python python-3.x

尝试从Json

中压缩别名密钥
{
    "name": "Rocky Marci",
    "aliases": ["Rocky", "Champ"],
    "physical": {
        "height_in": 67,
        "weight_lb": 150
    },
    "Fights": 49
}

喜欢以下

{
    "name": "Rocky Marci",
    "aliases.0": "Rocky",
    "aliases.1": "Champ",
    "physical.height_in": 67,
    "physical.weight_lb": 150,
    "Fights": 49
}

我试过这个

def flatten(d, parent_key='', sep='_'):
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, collections.MutableMapping):
            items.extend(flatten(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

但这并没有使数组变得平坦

2 个答案:

答案 0 :(得分:1)

您可以使用递归:

s = {
 "name": "Rocky Marci",
 "aliases": ["Rocky", "Champ"],
 "physical": {
    "height_in": 67,
    "weight_lb": 150
  },
  "Fights": 49
}
def flatten(d, last = ''):
   for a, b in d.items():
     if type(b) in [int, str]:
       yield ("{}.{}".format(a, last) if last else a, b)
     if isinstance(b, list):
       for i, c in enumerate(b):
         yield ("{}.{}".format(a, i), c)
     if isinstance(b, dict):
        for i in flatten(b, last = a):
           yield i

result = dict(list(flatten(s)))

输出:

{'aliases.0': 'Rocky', 'height_in.physical': 67, 'name': 'Rocky Marci', 'aliases.1': 'Champ', 'Fights': 49, 'weight_lb.physical': 150}

答案 1 :(得分:0)

因为list不是collections.MutableMapping的实例。我建议检查

isinstance(v, (list, dict))

代替。

更多可能性是here