【问题标题】:how to get dictionary elements names as list [duplicate]如何将字典元素名称作为列表[重复]
【发布时间】:2021-06-08 16:39:33
【问题描述】:

我有下面的字典,我需要提取“红色”和“蓝色”值作为列表,可能有比这两个更多的值。

输入:

js = {
    "accounts": {
        "red": {
            "client_id": "123",
            "client_secret": "123",
        },
        "blue": {
            "client_id": "123",
            "client_secret": "123",
        }
    }
}

预期输出:

["red","blue"]

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 看这个:dict.keys
  • @gribvirus74 谢谢,它有效
  • list(js['accounts'])?

标签: python json dictionary


【解决方案1】:

其实很简单。根本不需要使用dict.keys()...

js = {
    "accounts": {
        "red": {
            "client_id": "123",
            "client_secret": "123",
        },
        "blue": {
            "client_id": "123",
            "client_secret": "123",
        },
        "green": {
            "client_id": "123",
            "client_secret": "123",
        }
    }
}

print (list(js["accounts"]))

输出:

['red', 'blue', 'green']

【讨论】:

  • 你根本不需要.keys这个方法,你可以把它去掉,然后使用list(js['aacounts']))
猜你喜欢
  • 2014-04-09
  • 2015-01-01
  • 2018-02-08
  • 2019-03-15
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 2021-12-31
相关资源
最近更新 更多