如何将字典中的列表更改为键和他的值?

2024-06-06 17:37:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本这样的字典:

{
  '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
}

我怎样才能更改列表?。多谢各位


Tags: 列表model字典hpspecdesbrandmotor
3条回答
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

使用dict.popzip

Ex:

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}

如果你不需要它灵活的其他情况下,你可以做

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

相关问题 更多 >