Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,从dict列表中提取子dict的更有效的方法是什么?_Python_Python 3.x_Algorithm - Fatal编程技术网

在python中,从dict列表中提取子dict的更有效的方法是什么?

在python中,从dict列表中提取子dict的更有效的方法是什么?,python,python-3.x,algorithm,Python,Python 3.x,Algorithm,我有这样一个json: { "team": [ { "id": "1", "member_name": "name1", "some_other_key":"keyvalue1" }, { "id": "2", "member_name": "name2", "som

我有这样一个json:

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

        }
    ]
}
我想创造一个这样的dict

 { "1": "name1","2":"name2"}
user_mapping = {}
for user in users['team']:
    user_mapping[user['id']] = user['member_name'] 
我写过这样的代码

 { "1": "name1","2":"name2"}
user_mapping = {}
for user in users['team']:
    user_mapping[user['id']] = user['member_name'] 

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

简单明了:

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

此外,for-loop方法并不是一种蛮力。当需要更扩展的逻辑和中间语句/条件/表达式时,可以使用前一种方法。

简单明了:

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

此外,for-loop方法并不是一种蛮力。当您需要具有中间语句/条件/表达式的更扩展逻辑时,可以使用前一种方法。

是的,至少有一种:理解

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

理解比循环更快,也更具python风格

是的,至少有一个:理解

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

理解比循环更快,也更具python风格

dict理解除了蛮力,你怎么能做到这一点?您必须迭代所有项目。@jonrsharpe请参见answers@GPhilo不过,这两种方法都没有使用不同的算法,是吗?他们仍然是蛮力,因为他们不能走捷径去获得结果;这是一个基本的操作。听写理解除了暴力,你怎么能做到这一点?您必须迭代所有项目。@jonrsharpe请参见answers@GPhilo不过,这两种方法都没有使用不同的算法,是吗?他们仍然是蛮力,因为他们不能走捷径去获得结果;这是一个基本的操作。在这种情况下听写理解更快吗?@SujayDSa在这种情况下听写理解更快吗?@SujayDSa