[英]Python List: Weird Behavior When Disaggregating Dictionary Field
I have data stored in the following format: 我的数据以以下格式存储:
name address id
person place A123
person2 place2 A345
person3 place3 A445;A456
person4 place4 A333
I want to convert it to: 我想将其转换为:
name address id
person place A123
person2 place2 A345
person3 place3 A445
person3 place3 A456
person4 place4 A333
I'm trying to do it with this: 我正在尝试这样做:
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()
This code produces the equivalent of: 此代码产生的等效项为:
name address id
person place A123
person2 place2 A345
person3 place3 A456
person3 place3 A456
person4 place4 A333
Why isn't this working? 为什么这不起作用?
You're mutating the same dictionary, so you end up changing the id for both of your rows. 您要对同一个字典进行变异,因此最终要更改两行的ID。
By doing 通过做
combined_file_array[-1]['id'] = id.strip()
you're not only changing combined_file_array[-1]['id']
but also combined_file_array[-2]['id']
because they both point towards the same dict. 您不仅要更改
combined_file_array[-1]['id']
而且还要更改combined_file_array[-1]['id']
combined_file_array[-2]['id']
因为它们都指向同一个字典。
By appending the same dict row
in each iteration over ids
and updating the id
key to the same dict, you overwrite the value of the id
key in the previous iterations. 通过在每次迭代中将相同的字典
row
附加到ids
并将id
键更新为相同的dict,您将覆盖先前迭代中的id
键的值。
You should append a new copy of the dict from row
instead. 您应该从
row
追加字典的新副本。 Since you are going to update the id
key, you can pop
it first, and then use generic unpacking to update its value: 由于您将要更新
id
密钥,因此可以先将其pop
,然后使用通用拆包来更新其值:
for id in row.pop('id').split(';'):
combined_file_array.append({**row, 'id': id})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.