Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将字典中的列表更改为键,他';s值多少?_Python_List_Dictionary - Fatal编程技术网

Python 如何将字典中的列表更改为键,他';s值多少?

Python 如何将字典中的列表更改为键,他';s值多少?,python,list,dictionary,Python,List,Dictionary,我有一本这样的字典: { '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 } 我想让那本字典看起来像这样: { 'brand' : 'toyota

我有一本这样的字典:

{
  '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
}
我想让那本字典看起来像这样:

{
  '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={
“品牌”:“丰田”
“模型”:“花冠”
‘规格’:[‘电机’、‘cil’、‘hp’]
“des_spec”:[2.4,4187]
}
t=0#计数器
对于[“规格”]中的规格:#在规格上循环
a[spec]=des_spec[t]#插入字典、spec中的键、des_spec中的值
t+=1#在柜台上

使用
dict.pop
zip

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}
试试这个

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)

你做了什么来改变同样的情况?请提供您的代码。参见
d.update(dict(zip(d[“specs”]、d[“des_spec”]))
您错过了定义
des_spec=a[“des_spec”]”的一行代码。
。另外,对于一种更具python风格的方法,可以使用
for spec,val in zip(a['specs',a['des_spec']:
)来避免计数器。虽然这段代码可能会解决问题,但一个好的答案应该解释代码的作用以及它的帮助方式