[英]How to add value to the dictionary by checking the list and original dictionary python?
我有一個列表,其中包含從1到1500的ID。列表看起來像這樣
totalID = ['1','2','3',.......'1499','1500']
在字典中,某些ID的得分為(-1至4)
我想添加剩余的ID(totalID- dictionaryID),該ID不會出現在字典中且得分為“ 5”!
例如 :
Q216 .............. {'1': ['156'], '-1': ['506']}
新值是
{'1': ['156'], '-1': ['506'],
'5':['1','2','3','4','5',....'155','157'..'505','507','508',..'1500']}
如何根據totalID和originalDICT編輯詞典???
originalDICT={'Q216': {'1': ['156'], '-1': ['506']}, 'Q217': {'1': ['666', '667', '1395'], '3': ['668', '670', '1204', '1300', '37', '559', '630', '1107', '1213'], '2': ['1258', '1394'], '-1': ['1191'], '4': ['1391']}, 'Q214': {'3': ['833', '1361', '1362', '1363'], '-1': ['1294']}, 'Q215': {'-1': ['535'], '4': ['37', '35']}, 'Q212': {'3': ['885', '887', '886', '890', '769', '891', '1173', '843'], '2': ['888', '889', '1178'], '-1': ['1146'], '4': ['841', '1176', '1177']} }
for key, value in originalDICT.iteritems():
print key,".............. ", value
Q216 .............. {'1': ['156'], '-1': ['506']}
Q217 .............. {'1': ['666', '667', '1395'], '3': ['668', '670', '1204', '1300', '37', '559', '630', '1107', '1213'], '2': ['1258', '1394'], '-1': ['1191'], '4': ['1391']}
Q214 .............. {'3': ['833', '1361', '1362', '1363'], '-1': ['1294']}
Q215 .............. {'-1': ['535'], '4': ['37', '35']}
Q212 .............. {'3': ['885', '887', '886', '890', '769', '891', '1173', '843'], '2': ['888', '889', '1178'], '-1': ['1146'], '4': ['841', '1176', '1177']}
如何更新字典?
第一步是找到字典中已經存在的所有ID。 讓我們使用集合理解:
known_ids = {item for sublist in original_dict.values() for item in sublist}
接下來,讓我們用不known_ids
所有ID更新字典:
original_dict['5'] = [id for id in total_id if id not in known_ids]
如果您想要一本新詞典並希望保留original_dict
字典,請嘗試以下操作:
import copy
new_dict = copy.deepcopy(original_dict) # use deepcopy because you have mutable containers inside the dict
new_dict['5'] = [id for id in total_id if id not in known_ids]
如果可能有些東西已經分配給“ 5”,請嘗試以下方法:
original_dict['5'].extend(id for id in total_id if id not in known_ids)
注意,由於我們不需要多次創建創建的值,因此我已經從列表理解更改為生成器表達式。
編輯:基於(現在,顯然已刪除的注釋),如果total_id
是集合而不是列表,則可以使用集合操作。
total_id = set(total_id)
original_dict['5'] = list(total_id - known_ids)
# or
original_dict['5'].extend(total_id - known_ids)
根據幾個因素,這可能會或可能不會快於列表理解中的in
構造。
編輯2:鑒於OP的originalDICT
的實際格式,我們需要在以下方面做更多的工作:
known_ids = {key: {item for sublist in value.values() for item in sublist} for key, value in originalDICT.items()}
for key, known_id_set in known_ids.items():
originalDICT[key]['5'] = [id for id in total_id if id not in known_ids]
# or, if '5' is already populated
originalDICT[key]['5'].extend(id for id in total_id if id not in known_ids]
# or, if total_id is a set
originalDICT[key]['5'] = list(total_id - known_id_set)
因為這次我們僅更新最外面的詞典的一部分,所以很難理解詞典(這不太可能嗎?我還沒有考慮太多)。 這里的顯式for循環可能是更清晰的解決方案。
一班!
original_dict[5] = [i+1 for i in range(1500) if i not in original_dict]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.