[英]How can I change a list in a dictionary into a key and he's value?
我有一本這樣的字典:
{
'brand' : 'toyota'
'model' : 'corolla'
'specs' : ['motor', 'cil', 'hp']
'des_spec' : [2.4, 4, 187]
}
我希望那本字典看起來像這樣:
{
'brand' : 'toyota'
'model' : 'corolla'
'motor' : 2.4
'cil' : 4
'hp' : 187
}
我該如何更改該列表? 謝謝
如果你不需要它在其他情況下靈活,你可以做......
a = {
'brand' : 'toyota'
'model' : 'corolla'
'specs' : ['motor', 'cil', 'hp']
'des_spec' : [2.4, 4, 187]
}
t = 0 # Counter
for spec in a["specs"]: # Loop over the specs
a[spec] = des_spec[t] # Insert into dictionary, key from spec, value from des_spec
t += 1 # Up the counter
使用dict.pop
和zip
前任:
data = {
'brand' : 'toyota',
'model' : 'corolla',
'specs' : ['motor', 'cil', 'hp'],
'des_spec' : [2.4, 4, 187]
}
for k, v in zip(data.pop('specs'), data.pop('des_spec')):
data[k] = v
print(data)
# --> {'brand': 'toyota', 'cil': 4, 'hp': 187, 'model': 'corolla', 'motor': 2.4}
from collections import defaultdict
d1 = {
'brand' : 'toyota',
'model' : 'corolla',
'specs' : ['motor', 'cil', 'hp'],
'des_spec' : [2.4, 4, 187]
}
d2 = defaultdict()
for k,v in d1.items():
if type(v)!=list:
d2[k]=v
d3 = dict(zip(d1['specs'],d1['des_spec']))
d2.update(d3)
for k,v in d2.items():
print(k,v)
#brand toyota
#model corolla
#motor 2.4
#cil 4
#hp 187
嘗試這個;
d.update(dict(zip(d["specs"], d["des_spec"]))) #it will update the dictionary by adding spec's values as key and des_spec's values as value.
d.pop('specs')
d.pop('des_spec') #it will remove des_spec key:pair from the dictionary.
print(d)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.