Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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是一个转换为字典的函数吗?_Python_Dictionary_Lambda - Fatal编程技术网

Python是一个转换为字典的函数吗?

Python是一个转换为字典的函数吗?,python,dictionary,lambda,Python,Dictionary,Lambda,我有一个字典表示列表,如下所示: a = [{'score': 300, 'id': 3}, {'score': 253, 'id': 2}, {'score': 232, 'id': 1}] 我是python新手,我需要一个python lambda函数,它可以通过以下输出: dict = [{3:300}, {2:253}, {1:232}] 这样我就可以找到给定键的值 >>> print dict[3] >>> 300 我感谢你在这方面的帮助 不要

我有一个字典表示列表,如下所示:

a = [{'score': 300, 'id': 3}, {'score': 253, 'id': 2}, {'score': 232, 'id': 1}]
我是python新手,我需要一个python lambda函数,它可以通过以下输出:

dict = [{3:300}, {2:253}, {1:232}]
这样我就可以找到给定键的值

>>> print dict[3]
>>> 300
我感谢你在这方面的帮助

  • 不要使用
    dict
    作为变量名,因为这会影响内置类型名
    dict
  • {3300}
    不是字典,
    {3:300}
    您可以使用:

    或者为了向后兼容而提到的@Jon的dict构造函数,因为dict comp仅在py2.7+上可用:

    In [12]: import operator
        ...: dict(map(operator.itemgetter('id', 'score'), a))
    Out[12]: {1: 232, 2: 253, 3: 300}
    
  • 不要使用
    dict
    作为变量名,因为这会影响内置类型名
    dict
  • {3300}
    不是字典,
    {3:300}
    您可以使用:

    或者为了向后兼容而提到的@Jon的dict构造函数,因为dict comp仅在py2.7+上可用:

    In [12]: import operator
        ...: dict(map(operator.itemgetter('id', 'score'), a))
    Out[12]: {1: 232, 2: 253, 3: 300}
    


    为什么需要lambda?如果你试图将集合转换为dict条目,你会不高兴的。@user2357112不一定是lambda。。但主要目的是基于键获取值。即使有办法通过在集合“a”中提供id 3来查询300。这也有帮助。“这是背后的主要动机。”艾布拉姆斯同意。但你如何看待实现这个问题的上述动机呢。它可行吗?我不知道你为什么需要lambda。为什么需要lambda?如果你试图将集合转换为dict条目,你会不高兴的。@user2357112不一定是lambda..但主要目的是基于键获取值。即使有办法通过在集合“a”中提供id 3来查询300。这也有帮助。“这是背后的主要动机。”艾布拉姆斯同意。但你如何看待实现这个问题的上述动机呢。这可行吗?我不知道为什么你需要一个lambda。或者,一个非dict comp方法
    d=dict(map(operator.itemgetter('id','score'),a))
    @zhangxaochen这正是我要找的。多谢@JonClements thx提及,编辑了我的答案;)它只是看起来有点丑陋;P@Googler很乐意帮忙!如果您觉得它对您有用,请随时联系。:)@张晓晨:是的,很遗憾,迪克特的分数只有2.7+。。稍微好一点的方法是避免使用itemgetter,只使用genexp向dict提供一个2元组,或者OP想要一个lambda,
    dict(map(lambda L:L['id',L['score',a))
    :pOr,一种非dict comp方法
    d=dict(map(operator.itemgetter('id','score'),a))
    @zhangxaochen这正是我要找的。多谢@JonClements thx提及,编辑了我的答案;)它只是看起来有点丑陋;P@Googler很乐意帮忙!如果您觉得它对您有用,请随时联系。:)@张晓晨:是的,很遗憾,迪克特的分数只有2.7+。。稍微好一点的方法是避免使用itemgetter,只使用genexp向dict提供一个2元组,或者OP想要一个lambda,
    dict(map(lambda L:L['id',L['score',a))
    :p