遍历字典将类型转换为列表

时间:2019-01-03 18:40:51

标签: python list dictionary

我在python中有一个简单的字典。对于字典中的每个项目,我需要在每行上附加另一本字典(即5个联系人,每个联系人具有“名字”,“姓氏”,“性别”以及“其他”字段,它们都属于单个嵌入式字典。

我已附加了正在使用的循环。结果输出正是我想要的结果,但是当我在其上运行type()函数时,Python会将其作为列表而不是字典进行读取。如何将其转换回字典?

itemcount = 0
for item in dict_primarydata:
    dict_primarydata[itemcount]['otherData'] = dict_otherdata[itemcount]
    itemcount = itemcount+1

1 个答案:

答案 0 :(得分:0)

我要冒险猜一猜,dict_primarydatadict_otherdata看起来像这样:

dict_primarydata = [
  {
    'first_name': 'Kaylee',
    'last_name': 'Smith',
    'gender': 'f'
  },
  {
    'first_name': 'Kevin',
    'last_name': 'Hoyt',
    'gender': 'm'
  }
]

dict_otherdata = [
  {
    'note': 'Note about kaylee'
  },
  {
    'note': 'Note about kevin'
  }
]

好像dict_primarydatadict_otherdata被初始化为字典列表。换句话说,dict_primarydata实际上不是字典。这是一个包含几个字典的列表。

如果您希望输出为包含dict的{​​{1}},则需要执行转换。在进行转换之前,您需要确定将用什么作为外部字典的键。

侧注

由于您要遍历两个列表。基于范围的for循环会更具可读性:

dict
相关问题