我有两个格式的词典列表:

list1 = [
    {"time": "2024-01-29T18:32:24.000Z", "value": "abc"},
    {"time": "2024-01-30T19:47:48.000Z", "value": "def"},
    {"time": "2024-01-30T19:24:20.000Z", "value": "ghi"}
]

list2 = [
    {"time": "2024-01-30T18:34:44.000Z", "value": "xyz"},
    {"time": "2024-01-30T19:47:48.000Z", "value": "pqr"},
    {"time": "2024-01-30T19:24:20.000Z", "value": "jkl"}
]

Requirement : I need to compare value of "time" key of each dictionary in list1 with "time" key of each dictionary in list2 and if they are equal, will need to form a key value pair dictionary for subsequent lookups.
In the above, list1 and list2 have 2 dictionaries with same time :
"2024-01-30T19:47:48.000Z"
"2024-01-30T19:24:20.000Z"
I need to combine value of these 2 to form output as below :

Output:

{"def" : "pqr", "ghi" : "jkl"}

使用itertools.product函数,到目前为止,我可以按如下所示列出,但不能根据需要在键值对字典中列出.

import itertools

list1 = [{"time": "2024-01-29T18:32:24.000Z", "value": "abc"}, {"time": "2024-01-30T19:47:48.000Z", "value": "def"}, {"time": "2024-01-30T19:24:20.000Z", "value": "ghi"}]
list2 = [{"time": "2024-01-30T18:34:44.000Z", "value": "xyz"}, {"time": "2024-01-30T19:47:48.000Z", "value": "pqr"}, {"time": "2024-01-30T19:24:20.000Z", "value": "jkl"}]

output = [f"{x['value']} : {y['value']}"  if x['time'] == y['time'] else None for (x, y) in itertools.product(list1, list2)]
print(output)

Current Output :

[None, None, None, None, 'def : pqr', None, None, None, 'ghi : jkl']

I'm wondering if i can use lambda function to achieve output as : {"def" : "pqr", "ghi" : "jkl"}
Any help or suggestions is appreciated.

推荐答案

词典理解有一个if子句(在最后),也可以过滤掉元素,如下所示:

output = {x['value']: y['value'] for x, y in itertools.product(list1, list2) if x['time'] == y['time']}

输出:

{'def': 'pqr', 'ghi': 'jkl'}

Python相关问答推荐

如何在Pygame中绘制右对齐的文本?

如何计算部分聚合数据的统计数据

Pandas read_jsonfuture 警告:解析字符串时,to_datetime与单位的行为已被反对

"如果发生特定错误,返回值

Python中的函数中是否有充分的理由接受float而不接受int?

Deliveryter Notebook -无法在for循环中更新matplotlib情节(保留之前的情节),也无法使用动画子功能对情节进行动画

Gekko:Spring-Mass系统的参数识别

可变参数数量的重载类型(args或kwargs)

从numpy数组和参数创建收件箱

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

Python键入协议默认值

pyscript中的压痕问题

迭代嵌套字典的值

为一个组的每个子组绘制,

如何在表中添加重复的列?

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

使用Python查找、替换和调整PDF中的图像'

pandas:对多级列框架的列进行排序/重新排序

在方法中设置属性值时,如何处理语句不可达[Unreacable]";的问题?

使用Openpyxl从Excel中的折线图更改图表样式