[英]Python List: Weird Behavior When Disaggregating Dictionary Field
我的数据以以下格式存储:
name address id
person place A123
person2 place2 A345
person3 place3 A445;A456
person4 place4 A333
我想将其转换为:
name address id
person place A123
person2 place2 A345
person3 place3 A445
person3 place3 A456
person4 place4 A333
我正在尝试这样做:
combined_file_array = []
for index, row in enumerate(data):
if (';' not in row['id']):
combined_file_array.append(row)
else:
ids = row['id'].split(';')
for id in ids:
combined_file_array.append(row)
combined_file_array[-1]['id'] = id.strip()
此代码产生的等效项为:
name address id
person place A123
person2 place2 A345
person3 place3 A456
person3 place3 A456
person4 place4 A333
为什么这不起作用?
您要对同一个字典进行变异,因此最终要更改两行的ID。
通过做
combined_file_array[-1]['id'] = id.strip()
您不仅要更改combined_file_array[-1]['id']
而且还要更改combined_file_array[-1]['id']
combined_file_array[-2]['id']
因为它们都指向同一个字典。
通过在每次迭代中将相同的字典row
附加到ids
并将id
键更新为相同的dict,您将覆盖先前迭代中的id
键的值。
您应该从row
追加字典的新副本。 由于您将要更新id
密钥,因此可以先将其pop
,然后使用通用拆包来更新其值:
for id in row.pop('id').split(';'):
combined_file_array.append({**row, 'id': id})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.