我对python dict update有疑问。我有两个字典,如下所述。
dict1={1:{"partname": 'part1_item1' , 'archname':'sca_item1_rev1.0.jar','rev: '1.0', 'compname': item1},
2:{"partname": 'part1_item2' , 'archname':'sca_item2_rev2.0.jar','rev: '2.0' ,'compname': item2},
3:{"partname": 'part1_item3' , 'archname':'sca_item3_rev2.0.jar','rev: '2.0' ,'compname': item3}}
dict2={item1:{'jarversion': '1.0', 'jarname':'item1', 'partition': 'item1'},
item2:{'jarversion': '1.0', 'jarname':'item2', 'partition': 'item2'},
item1:{'jarversion': '2.0', 'jarname':'item3', 'partition': 'item3'}}
我想将dict1的值(rev和jarname)与dict2进行比较,如果jatname和jar版本相同,那么我需要在dict1中使用'overwrite':'true'
更新如果两个版本都不相同并且找不到版本,那么我需要在dict1中使用'overwrite':'false'更新
使用dict1尝试创建代码,如下所述
i=1
for root, dirs, files in os.walk(comp):
if files:
if i not in dict1.keys():
dict1[i] = {}
if '\\' in root:
subdir=root.split('\\')[1]
else:
subdir=''
dict1[i].update({"partname" : '', "archname": '', "compname":'', "rev": ''})
if subdir:
dict1[i].update({"partname" : '%s'%subdir })
dict1[i].update({"archname": '', "compname":'', "rev": ''})
for filename in files:
if filename.endswith('.jar'):
dict1[i].update({"archname": '%s'%filename,"compname": ('%s' %filename).split('sca_')[1].split('_rev')[0],"rev": ('%s' %filename).split('sca_')[1].split('_rev')[1].split('.jar')[0]})
else:
print("Unrecognised file: %s"%(filename))
i=i+1
dict2已经创建。
我需要使用以下格式更新字典。
if dict1(compname)(rev) == dict2 (jarversion)(jarname)
dict1={1:{"partname": 'part1_item1' , 'archname':'sca_item1_rev1.0.jar','rev: '1.0', 'compname': item1 , 'overwrite' :'true'}}
if dict1(compname)(rev) != dict2 (jarversion)(jarname)
dict1={1:{"partname": 'part1_item1' , 'archname':'sca_item1_rev1.0.jar','rev: '1.0', 'compname': item1 , 'overwrite' :'false'}}
请帮助我如何使用此键(值)更新字典。
答案 0 :(得分:0)
让我们尝试一下
# create a look-up set for unique (jarname + jarversion)
look_up = {v['jarname'] + v['jarversion'] for k, v in dict2.items()}
# use dict-comprehension for updating the values back to dict1
print(
{k: {**v, **{"overwrite": v['compname'] + v['rev'] in look_up}}
for k, v in dict1.items()}
)
EDIT ,较旧的python
look_up = set()
for _, v in dict2.items():
look_up.add(v['jarname'] + v['jarversion'])
for k, v in dict1.items():
dict1[k].update(
{"overwrite": str(v['compname'] + v['rev'] in look_up).lower()}
)