更改字典列表中特定键的值

时间:2019-07-11 18:43:34

标签: python-3.x

我想更新词典列表中特定键的值。

例如,我有以下词典列表(输入值):

   deviceDynamics = [{'updated': '2019-07-10T10:27:44.763Z',
                  'created': '2019-07-10T10:27:44.763Z'},
                  {'updated': '2019-07-10T10:27:44.763Z',
                  'created': '2019-07-10T10:27:44.763Z'},
                  {'updated': '2019-07-10T10:27:44.763Z',
                  'created': '2019-07-10T10:27:44.763Z'}]

我的代码是-

for d in deviceDynamics:
    timestamp = ((datetime.strptime(d['updated'], '%Y-%m-%dT%H:%M:%S.%fZ')) - datetime(1970, 1, 1)).total_seconds()


    d = next(d for d in deviceDynamics)
    d['updated'] = timestamp

    print(deviceDynamics)

不是更改每个created键值,而是更改第一个键值。以下是输出-

[{'created': '2019-07-10T10:27:44.763Z', 'updated': 1562754464.763}, {'created': '2019-07-10T10:27:44.763Z', 'updated': '2019-07-10T10:27:44.763Z'}, {'created': '2019-07-10T10:27:44.763Z', 'updated': '2019-07-10T10:27:44.763Z'}]

但是它并没有改变其他created键的值...请提出任何建议

1 个答案:

答案 0 :(得分:0)

删除将d设置为等于始终停留在第一项上的新迭代器的行。

for d in deviceDynamics:
    timestamp = ((datetime.strptime(d['updated'], '%Y-%m-%dT%H:%M:%S.%fZ')) -datetime(1970, 1, 1)).total_seconds()

    d['updated'] = timestamp

    print(deviceDynamics)

如果您想使用更新后的KV对打印整个列表,请在for循环外添加一条打印语句。

for d in deviceDynamics:
    timestamp = ((datetime.strptime(d['updated'], '%Y-%m-%dT%H:%M:%S.%fZ')) - datetime(1970, 1, 1)).total_seconds()

    d['updated'] = timestamp

print(deviceDynamics)

相关问题