如何在Python中更新字典中键字段的值?

时间:2019-05-30 11:31:24

标签: python

我有如下字典:

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

我写了下面的程序来从字典中检索键:

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for keys in test.keys():
    print(keys)

当我们在keys字段中获得数字值时,我想更新keys字段值。以上字典中的示例

keys: 100
value: 271

当键值是整数时,我想更新键值,例如 xx_100:271

我想使用python以最简单的方式解决问题。

4 个答案:

答案 0 :(得分:1)

尝试一下

>>> test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

>>> dict(("xx_{}".format(k),v) if isinstance(v,int) else (k,v) for k,v in test.items())
{'xx_100': 271, 'updated_at': {'date': '2017-10-14T12:15:52.172Z'}, 'created_at': {'date': '2017-10-14T12:15:52.172Z'}}

答案 1 :(得分:0)

尝试一下。

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}
for key in test.keys():
    try:
        if type(key)==int:
            test['xx_'+str(key)]=test.pop(key)
    except: pass

答案 2 :(得分:0)

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for keys in test.keys():

if isinstance(test[keys], int):
    test[keys] = "xx_" + str(test[keys])

 print(test)

答案 3 :(得分:0)

您不仅需要循环user_contacts = Contact.objects.order_by('-Contact_date').filter(user_id=request.user.id) ,还需要循环keyskey来测试哪个值是value类型。下面的代码可以做到这一点:

int