我在Python中有一个字典列表如下:
comment_obj=
[{'food_id': '-KCRZfJMGvYkofzskfRv',
'food_name': 'Lazeez Special Cheese Kabab',
'text': 'Lazeez Special Cheese Kebab were completely drool worthy',
'time_stamp': '',
'user_id': '-KBIcIgaIOYh2G8hLrYj',
'user_name': 'Arjun Nambiar'},
{'food_id': '-KCRZfJMGvYkofzskfRv',
'food_name': 'Lazeez Special Cheese Kabab',
'text': 'This is heart attack on a plate.So yummy and gooey',
'time_stamp': '',
'user_id': '-KBIcIgfu1V735jviWrk',
'user_name': 'Samir Madhavan'},
{'food_id': '-KCRZfJMGvYkofzskfRv',
'food_name': 'Lazeez Special Cheese Kabab',
'text': 'The molten cheese on this chicken was just awesome',
'time_stamp': '',
'user_id': '-KBIcIggKo4I7Bkn-N48',
'user_name': 'Febin Sathar'},
{'food_id': '-KCRZfJRMgLjlqzKZzCI',
'food_name': 'Chicken Reshmi Kebab',
'text': 'Covered in a velvet coating of egg,this was so yumm',
'time_stamp': '',
'user_id': '-KBIcIgaIOYh2G8hLrYj',
'user_name': 'Arjun Nambiar'}]
很明显,time_stamp值为空。我需要更新每个dict中的time_stamp值,以便后续dict中的time_stamp比前一个dict多一个。这就是我尝试这样做的方式:
epoch_time = 1459408412
for d in comment_obj:
d.update((k, epoch_time+1) for k, v in d.iteritems() if k == "time_stamp")
但这会将time_stamp更新为1459408413并且计数器不会增加。我做错了什么?
答案 0 :(得分:1)
def new
@event = current_user.events.build
end
答案 1 :(得分:1)
实际上,您不应该遍历字典中的键或使用update()
方法更新一个键。只需使用dict
查找。
>>> epoch_time = 1459408412
>>> for element in comment_obj:
... epoch_time = epoch_time + 1
... element['time_stamp'] = epoch_time
...
>>> [element['time_stamp'] for element in comment_obj] # Just to confirm all elements are updated.
[1459408413, 1459408414, 1459408415, 1459408416]