我想从现有词典列表中选择一些键,并通过查找另一张地图来添加其他键。
主要列表如下
result=[{'key1':123,'key2':'prod','key3':'abc','key4':'cde'},{'key1':123,'key2':'prod','key3':'def','key4':'qrs'},{'key1':321,'key2':'sale','key3':'dssd','key4':'cfde'}]
新列表中需要的密钥如下,key5
和key6
是需要添加的新密钥
wantedkeys=['key1','key3','key5','key6']
字典用于添加新的键值
keyMap={(123, 'key5'): 'abc', (123, 'key6'): 'pqr'}
我可以使用以下语法选择key1
和key3
来获取输出。
new_list = [{ key: record[key] for key in wantedkeys } for record in result if record['key2']=='prod']
但是在扩展它的同时还添加了其他键时,出现语法错误。
new_list = [{ key : keyMap[record['key1'],key] if key in ['key5','key6'] else key: record[key] for key in wantedkeys } for record in result if record['key2']=='Prod']
我知道可以通过遍历列表来完成此操作,但是由于我的列表将有几百万条记录,因此还有更多的Python方式可以实现更好的性能吗? 任何帮助将不胜感激
更新:获得了解决方案。希望这会有所帮助
new_list = [dict({ key: record[key] for key in ['key1','key3']},key5=keyMap[record['key1'],'key5'],key6=keyMap[record['key1'],'key6']) for record in result if record['key2']=='prod']
答案 0 :(得分:0)
得到解决方案。希望这会有所帮助
new_list = [dict({ key: record[key] for key in ['key1','key3']},key5=keyMap[record['key1'],'key5'],key6=keyMap[record['key1'],'key6']) for record in result if record['key2']=='prod']