这是我的下面的代码,我想将jsondict值添加到parsedData列表
parsedData = []
userData = {}
jsondict=[{u'Name': u'BILL', u'ID': u'1028', u'CARS': [u'BMW', u'AUDI']},
{u'Name ': u'TOM', u'ID': u'1029', u'CARS': [u'TOYOTA', u'FERRARI']}]
for distro in jsondict:
userData['Name'] = distro['Name']
userData['ID'] = distro['ID']
userData['CARS1'] = distro['CARS'][0]
userData['CARS2'] = distro['CARS'][1]
parsedData.append(userData)
但是从这段代码中我得到两次最后一次dict,这是不正确的,预期输出应该是这样的:
[{u'Name': u'BILL', u'ID': u'1028', u'CARS1': u'BMW',u'CARS2': u'AUDI'},
{u'Name ': u'TOM', u'ID': u'1029', u'CARS1': u'TOYOTA', u'CARS2':u'FERRARI'}]
答案 0 :(得分:2)
您可以在Python3中使用字典解压缩:
jsondict=[{u'Name': u'BILL', u'ID': u'1028', u'CARS': [u'BMW', u'AUDI']},
{u'Name ': u'TOM', u'ID': u'1029', u'CARS': [u'TOYOTA', u'FERRARI']}]
final_listing = [{**{a:b for a, b in i.items() if a != 'CARS'}, **{'CARS{}'.format(i):a for i, a in enumerate(i['CARS'], start=1)}} for i in jsondict]
输出:
[{'Name': 'BILL', 'ID': '1028', 'CARS1': 'BMW', 'CARS2': 'AUDI'}, {'Name ': 'TOM', 'ID': '1029', 'CARS1': 'TOYOTA', 'CARS2': 'FERRARI'}]
编辑:Python2解决方案:
last_data = [dict([(a, b) for a, b in i.items() if a != 'CARS']+[('CARS{}'.format(i), a) for i, a in enumerate(i['CARS'], start=1)]) for i in jsondict]
输出:
[{'Name': 'BILL', 'ID': '1028', 'CARS1': 'BMW', 'CARS2': 'AUDI'}, {'Name ': 'TOM', 'ID': '1029', 'CARS1': 'TOYOTA', 'CARS2': 'FERRARI'}]
答案 1 :(得分:2)
您正在引用相同的dict两次(parsedData[0] is parsedData[1]
计算结果为true)。要阻止这种情况发生,只需在循环中创建dict:
parsedData = []
jsondict=[{u'Name': u'BILL', u'ID': u'1028', u'CARS': [u'BMW', u'AUDI']},
{u'Name ': u'TOM', u'ID': u'1029', u'CARS': [u'TOYOTA', u'FERRARI']}]
for distro in jsondict:
userData = {}
userData['Name'] = distro['Name']
userData['ID'] = distro['ID']
userData['CARS1'] = distro['CARS'][0]
userData['CARS2'] = distro['CARS'][1]
parsedData.append(userData)