【问题标题】:What is a more efficient way to extract sub-dicts from a list of dicts in python?从python中的dicts列表中提取子dicts的更有效方法是什么?
【发布时间】:2020-02-13 02:39:18
【问题描述】:

我有一个这样的 json:

{
    "team": [
        {
            "id": "1",
            "member_name": "name1",
            "some_other_key":"keyvalue1"                
        },
        {
            "id": "2",
            "member_name": "name2",
            "some_other_key": "keuvalue2"

        }
    ]
}

我想创建一个这样的字典

 { "1": "name1","2":"name2"}

我写过这样的代码

user_mapping = {}
for user in users['team']:
    user_mapping[user['id']] = user['member_name'] 

但我想知道是否有比我使用的蛮力方法更 Pythonic 或有效的方法来做到这一点。

【问题讨论】:

  • 字典理解
  • 除了“蛮力”之外,你怎么能这样做其他?您必须遍历所有项目。
  • @jonrsharpe 查看答案
  • @GPhilo 两者都没有使用不同的算法,不是吗?他们仍然是蛮力,因为他们不能走捷径来获得结果;这基本上是一个 O(n) 操作。

标签: python python-3.x algorithm


【解决方案1】:

简单明了:

user_mapping = {user['id']: user['member_name'] for user in users['team']}

此外,您的 for loop 方法不是“蛮力”。当您需要更扩展的逻辑(使用中间语句/条件/表达式)时,您将使用前一种方法。

【讨论】:

【解决方案2】:

是的,至少有一个:理解

user_mapping = { user['id']:user['member_name'] for user in users['team'] }

理解比 for 循环更快,更 Python 化

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-28
    • 2015-06-08
    • 2021-02-04
    • 2017-12-27
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    相关资源
    最近更新 更多