我正在向字典中添加一个带有值的新键,但在运行代码时仍然会遇到运行时错误。我在同一次迭代中添加了两个单独的键。我可以让它在添加一个密钥时运行,但不能同时添加两个密钥。
向dict添加不起作用的条目的代码:
for data in list:
for value in data:
if value == 'timestamp':
timestamp = data[value]
minute_shred = timestamp[14:16]
second_shred = timestamp[17:19]
#change to x,y
if minute_shred[0] == '0' and second_shred[0] == '0':
minute_shred = timestamp[15:16]
second_shred = timestamp[17:19]
data['minute'] = int(minute_shred)
data['second'] = int(minute_shred)
print(data['second'], timestamp)
#no change to x,y
elif minute_shred[0] != '0' and second_shred[0] != '0':
data['minute'] = int(minute_shred)
data['second'] = int(minute_shred)
print(data['second'], timestamp)
# change to x, not y
elif minute_shred[0] == '0' and second_shred[0] != '0':
minute_shred = timestamp[15:16]
data['minute'] = int(minute_shred)
data['second'] = int(second_shred)
print(data['second'], timestamp)
#change to y, not x
elif minute_shred[0] != '0' and second_shred[0] == '0':
second_shred = timestamp[18:19]
data['second'] = int(second_shred)
data['minute'] = int(minute_shred)
print(data['second'], timestamp)当在迭代中仅添加一个键时,此代码可以工作。
for data in list:
for value in data:
if value == 'timestamp':
timestamp = data[value]
minute_shred = timestamp[14:16]
if minute_shred[0] == '0':
minute_shred = timestamp[15:16]
data['minute'] = int(minute_shred)
elif minute_shred[0] != '0':
data['minute'] = int(minute_shred)我也尝试了一个接一个地添加它们,但没有成功,第二个for循环使用了添加数据的第二个逻辑,因为它产生了运行时错误。我确实注意到,如果在添加second_shred变量时将数据“‘second”更改为“data”adding,则可以正常工作。显然,我需要将它们添加为两个单独的键。
发布于 2019-12-13 15:25:49
正如其他人所提到的,不要在迭代时修改迭代器。
如果您想迭代和修改数据,我强烈建议使用map或列表理解。
示例:
def modify(dict_val):
# Code for modification as in your question
list = [map(modify, data) for data in list]如果您不想将其用于将来的迭代,请确保在此为Python3的情况下将映射包装在list()中。
发布于 2019-12-13 15:42:52
使用deepcopy工作。
listcopy = copy.deepcopy(list)
for item in listcopy:
itemcopy = copy.deepcopy(item)
for k in itemcopy:
if k == 'timestamp':
timestamp = item[k]
second_shred = timestamp[17:19]
if second_shred[0] == '0':
second_shred = timestamp[18:19]
item['second'] = int(minute_shred)
elif second_shred[0] != '0':
item['second'] = int(minute_shred)https://stackoverflow.com/questions/59317594
复制相似问题