【问题标题】:Create a dictionary where the key is a key from a dictionary and the value is a value from another key in a nested dictionary创建一个字典,其中键是字典中的键,值是嵌套字典中另一个键的值
【发布时间】:2020-10-03 23:57:16
【问题描述】:

我正在寻找在嵌套字典中创建一个字典,其中键是 store,值是 store_type。我希望它输出带有 store 的键和值的字典:store_type

我已经尝试过,但无法让 storestore_type 在没有出现类型或属性错误的情况下返回:

def get_store(large_dict):
    for i in large_dict:
        name = i["store"]
        party = i["store_type"]

下面的示例代码

    "parent": 116,
    "child": 2,
    "group": "member",
    "bucket_number": 130,
    "source": "https://www.webiste.com/",
    "url": "hhttps://www.website.com/",
    "preference": {},
    },
    {
    "order": 3241235,
    "store": "Target",
    "description": "Expect More, Pay Less",
    },
    "previous_orders": [
        {
            "order_id": "0213124",
            "store": "Target",
            "store_type": "Retail",
            "state": "AL",
        },
        {
            "order_id": "0213125",
            "store": "Publix",
            "store_type": "Grocery",
            "state": "AL",
        },
        {
            "order_id": "0213126",
            "store": "Winn-Dixie",
            "store_type": "Grocery",
            "state": "AL",
        },
        {
            "order_id": "0213127",
            "store": "Sur la Table",
            "store_type": "Retail",
            "state": "AL",
        },
        {
            "order_id": "0213128",
            "store": "Trader Joes",
            "store_type": "Grocery",
            "state": "AL",
        }

【问题讨论】:

  • 显示你的回溯

标签: python python-3.x dictionary


【解决方案1】:

for i in large_dict: 有什么用?我很难说出这个问题的标题在问什么,但看起来你只想做这样的事情。

new_dict = {}

for order in large_dict["previous_orders"]:
    store = order["store"]
    store_type = order["store_type"]
    new_dict[store] = store_type

【讨论】:

  • 这可能意味着large_dict 不是字典。您可能需要检查它是否确实是您所期望的。
  • 是的,所以我尝试创建一个字典 = {},然后调用 i["store"] 和 i["store_type],然后使用 new_dict[store] = 在新字典中创建条目store_type,但我不断收到类型错误:列表索引必须是整数或切片,而不是 str
  • 很确定这是一本字典
  • [ { "description": "abcdefghijklm", "previous_orders": [ { "store": "Target", "store_type": "Retail" } ] } ] 如果它在括号中,我假设它是列表中的字典,但我仍然不确定如何实现我需要的目标
  • @sab 因为听起来它可能不应该在列表中,您可以在运行此代码之前添加一行将其取出。 large_dict = large_dict[0].
猜你喜欢
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多