我有两个格式的词典列表:
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.