我有一份字典 list ,如下所示:

    sample = [{'By': {'email': 'xyz@stackoverflow.com', 'name': 'xyzzy', 'id': '5859'}},{'By': {'email': 'abc@stackoverflow.com', 'name': 'abccb', 'id': '9843'}},
{'By': {'email': 'xyz@stackoverflow.com', 'name': 'xyzzy', 'id': '5859'}}]

From this, I am trying to access keys 'name' and 'id' and write distinct values into a dictionary.
Below is returning id's alone :

print(set(map(lambda x: x['By']['id'], sample)))

output:{‘9843’,‘5859’}

Required output:{"9843":"abccb","5859":"xyzy"}

我try 使用f-字符串将‘id’和‘name’值连接在一起,中间用冒号(:)表示列表中每个词典条目的"id:name"格式.

set(map(lambda x: f"{x['By']['id']}:{x['By']['name']}", sample))

output:{‘9843:abccb’,‘5859:xyzy’}

是否可以访问map lambda函数中两个键的值?谢谢.

推荐答案

你想要dict分,不是set分.您可以获取lambda中的所有值,并将它们打包到tuple

print(dict(map(lambda x: (x['By']['id'], x['By']['name']), sample)))

你也应该考虑一个更简单的解决方案,你在这里不需要maplambda,词典理解就可以了

print({x['By']['id']: x['By']['name'] for x in sample})

Python相关问答推荐

如何将 map 数组组合到pyspark中每列的单个 map 中

回归回溯-2D数组中的单词搜索

如何判断. text文件中的某个字符,然后读取该行

来自ARIMA结果的模型方程

使用Curses for Python保存和恢复终端窗口内容

在Python中,什么表达相当于0x1.0p-53?

customtkinter中使用的这个小部件的名称是什么

按 struct 值对Polars列表[struct[]]排序

如何获取Django REST框架中序列化器内部的外卡属性?

如何使用Selenium访问svg对象内部的元素

给定数据点,制定它们的关系

阅读Polars Python中管道的函数定义

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

未知依赖项pin—1阻止conda安装""

* 动态地 * 修饰Python中的递归函数

如何在PySide/Qt QColumbnView中删除列

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''

如何使用正则表达式修改toml文件中指定字段中的参数值

从一个df列提取单词,分配给另一个列

查看pandas字符列是否在字符串列中