将嵌套字典标准化为单个字典

时间:2018-11-14 13:05:21

标签: python python-3.x

我具有从文件读取的实际结构:

{
  "id": 1,
  "name": "Explosives",
  "category_id": 1,
  "average_price": 294,
  "is_rare": 0,
  "max_buy_price": 755,
  "max_sell_price": 1774,
  "min_buy_price": 99,
  "min_sell_price": 18,
  "buy_price_lower_average": 176,
  "sell_price_upper_average": 924,
  "is_non_marketable": 0,
  "ed_id": 128049204,
  ** "category": {
    "id": 1,
    "name": "Chemicals"
  } **
}

我正在尝试创建一个列表,然后插入数据库。词典末尾的数据也应该在列表的末尾。

正如您在下面看到的,我的词典末尾有词典。我的实际代码-可以正常工作-是:

 for v in d:
        commodities_reference = []
        for k, g in v.items():
            if isinstance(g, dict):
                dict1 = g
                my_value1 = dict1.get("id")
                my_value2 = dict1.get("name")

        for s, i in v.items():
            if not isinstance(i, dict):
                commodities_reference.append(i)
        commodities_reference.append(my_value1)
        commodities_reference.append(my_value2)  

尽管如此,我想知道是否还有一种更“ pythonic”的方式来执行此操作,因为它对我来说看起来有点难看。

谢谢。

1 个答案:

答案 0 :(得分:0)

v = {
    "id": 1,
    "name": "Explosives",
    "category_id": 1,
    "average_price": 294,
    "is_rare": 0,
    "max_buy_price": 755,
    "max_sell_price": 1774,
    "min_buy_price": 99,
    "min_sell_price": 18,
    "buy_price_lower_average": 176,
    "sell_price_upper_average": 924,
    "is_non_marketable": 0,
    "ed_id": 128049204,
    "category": {
        "id": 1,
        "name": "Chemicals"
    }
}

commodities_reference = []

for val in v.values():
    if isinstance(val, dict):
        commodities_reference.extend(val.values())
    else:
        commodities_reference.append(val)

print(commodities_reference)

或者,如果您想简洁明了但可读性较差:

for val in v.values():
    commodities_reference += val.values() if isinstance(val, dict) else [val]