我有一个list
和一个dictionary
像这样的:
mydict = {
'some-id-string1': {'name': 'Saeed1', 'phone': '+989307333730', 'id': 'abc'},
'some-id-string2': {'name': 'Saeed2', 'phone': '+989307333731', 'id': 'def'},
'some-id-string3': {'name': 'Saeed3', 'phone': '+989307333732', 'id': 'ghi'},
'some-id-string4': {'name': 'Saeed3', 'phone': '+989307333733', 'id': 'jkl'},
'some-id-string5': {'name': 'Saeed3', 'phone': '+989307333730', 'id': 'abc'},
'some-id-string6': {'name': 'Saeed3', 'phone': '+989307333730', 'id': 'abc'},
'some-id-string7': {'name': 'Saeed3', 'phone': '+989307333731', 'id': 'def'},
}
mylist = [
{'id': 'abc', 'name': 'some_name1'},
{'id': 'def', 'name': 'some_name2'},
{'id': 'ghi', 'name': 'some_name3'},
]
我将检查id
的值是否mydict
匹配mylist
并将 添加name
到mylist
。mydict
如果不存在,我将有两个输出(因为我目前不确定要保留哪一个,所以我将同时保留这两个,以便稍后决定):
如果存在则预期输出 1 ,如果不存在则name
添加:NOT_FOUND
name
newmydict1 = {
'some-id-string1': {'name': 'Saeed1', 'phone': '+989307333730', 'id': 'abc', 'id_name': 'some_name1'},
'some-id-string2': {'name': 'Saeed2', 'phone': '+989307333731', 'id': 'def', 'id_name': 'some_name2'},
'some-id-string3': {'name': 'Saeed3', 'phone': '+989307333732', 'id': 'ghi', 'id_name': 'some_name3'},
'some-id-string4': {'name': 'Saeed3', 'phone': '+989307333733', 'id': 'jkl', 'id_name': 'NOT_FOUND'},
'some-id-string5': {'name': 'Saeed3', 'phone': '+989307333730', 'id': 'abc', 'id_name': 'some_name1'},
'some-id-string6': {'name': 'Saeed3', 'phone': '+989307333730', 'id': 'abc', 'id_name': 'some_name1'},
'some-id-string7': {'name': 'Saeed3', 'phone': '+989307333731', 'id': 'def', 'id_name': 'some_name2'},
}
如果存在则预期输出 2 name
,并为没有对应的创建一个新列表name
:
newmydict2 {
'some-id-string1': {'name': 'Saeed1', 'phone': '+989307333730', 'id': 'abc', 'id_name': 'some_name1'},
'some-id-string2': {'name': 'Saeed2', 'phone': '+989307333731', 'id': 'def', 'id_name': 'some_name2'},
'some-id-string3': {'name': 'Saeed3', 'phone': '+989307333732', 'id': 'ghi', 'id_name': 'some_name3'},
'some-id-string5': {'name': 'Saeed3', 'phone': '+989307333730', 'id': 'abc', 'id_name': 'some_name1'},
'some-id-string6': {'name': 'Saeed3', 'phone': '+989307333730', 'id': 'abc', 'id_name': 'some_name1'},
'some-id-string7': {'name': 'Saeed3', 'phone': '+989307333731', 'id': 'def', 'id_name': 'some_name2'},
}
newmydict3 = {
'some-id-string4': {'name': 'Saeed3', 'phone': '+989307333733', 'id': 'jkl'},
}
我不知道该做什么,该写什么,因为key
的mydict
(我的意思是some-id-string
)在中不存在mylist
,并且的某些成员mydict['id']
出现了多次。
我试过
new = [{
'string_id': d,
'id': l['id'],
'id_name': l['name'],
'phone': mydict[d]['phone'],
'name': mydict[d]['name']
} for l in mylist for d in mydict if mydict[d]['id'] == l['id']
]