修改字典键

时间:2018-08-10 07:29:16

标签: python python-3.x

嗨,我有如下的字典

{
'namelist': [{'name':"John",'age':23,'country':'USA'},
                   {'name':"Mary",'age':12,'country':'Italy'},
                   {'name':"Susan",'age':32,'country':'UK'}],
'classteacher':'Jon Smith'
}

我想知道是否可以将其更改为

 {
 'namelist': [{'name_1':"John",'age_1':23,'country_1':'USA'},
               {'name_2':"Mary",'age_2':12,'country_3':'Italy'},
               {'name_3':"Susan",'age_3':32,'country_3':'UK'}],
 'classteacher':'Jon Smith'
 }

通过在每个键的最后一个位置上添加_1,_2 .... 可能吗?谢谢您的帮助

7 个答案:

答案 0 :(得分:2)

您可以通过更改键并删除初始值yourdict[j+'_'+str(num)] = yourdict.pop(j)

在初始列表中添加新值。

keys()返回字典的所有键(在您的情况下为name, age, country

a = {'namelist': [{'name':"John",'age':23,'country':'USA'},
                  {'name':"Mary",'age':12,'country':'Italy'},
                  {'name':"Susan",'age':32,'country':'UK'}]}

num = 1
for i in a['namelist']:
    for j in list(i.keys()):
        i[j+'_'+str(num)] = i.pop(j)
    num += 1

print(a)
# {'namelist': [
#    {'name_1': 'John', 'country_1': 'USA', 'age_1': 23}, 
#    {'name_2': 'Mary', 'country_2': 'Italy', 'age_2': 12}, 
#    {'name_3': 'Susan', 'age_3': 32, 'country_3': 'UK'}]}

答案 1 :(得分:0)

使用enumerate

例如:

d = {'namelist': [{'name':"John",'age':23,'country':'USA'},
               {'name':"Mary",'age':12,'country':'Italy'},
               {'name':"Susan",'age':32,'country':'UK'}]}

d["namelist"] = [{k+"_"+str(i): v for k,v in value.items()} for i , value in enumerate(d["namelist"], 1)]
print(d)  

输出:

{'namelist': [{'age_1': 23, 'country_1': 'USA', 'name_1': 'John'},
              {'age_2': 12, 'country_2': 'Italy', 'name_2': 'Mary'},
              {'age_3': 32, 'country_3': 'UK', 'name_3': 'Susan'}]}

答案 2 :(得分:0)

您将必须创建新密钥,其值对应于旧密钥。您可以使用dict.pop

轻松地实现这一目标

我假设您要将行的索引添加到字段name中。对于其他字段或以其他方式对其进行修改,您可以执行类似的操作。

for index, row in enumerate(a['namelist']):
    row['name_%d' % index] = row.pop('name')

输出:

{'namelist': [{'age': 23, 'country': 'USA', 'name_0': 'John'},
  {'age': 12, 'country': 'Italy', 'name_1': 'Mary'},
  {'age': 32, 'country': 'UK', 'name_2': 'Susan'}]}

答案 3 :(得分:0)

这是我的单行样式解决方案,即使您除了“名称列表”以外还有很多键,它也可以使用:

d = {'namelist': [{'name':"John",'age':23,'country':'USA'},
                   {'name':"Mary",'age':12,'country':'Italy'},
                   {'name':"Susan",'age':32,'country':'UK'}],
     'classteacher':'Jon Smith'
    }


d = {k:[{f'{k2}_{nb}':v2 for k2,v2 in i.items()} for nb,i in enumerate(v,1)] if isinstance(v,list) else v for k,v in d.items()}

print(d)
# {'namelist': [{'name_1': 'John', 'age_1': 23, 'country_1': 'USA'},
#               {'name_2': 'Mary', 'age_2': 12, 'country_2': 'Italy'},
#               {'name_3': 'Susan', 'age_3': 32, 'country_3': 'UK'}]}, 
#  'classteacher': 'Jon Smith'
# }

但是,正如Aran-Fey所说,这并不是很容易理解,而且很难维护。因此,我也建议您使用嵌套的for循环解决方案:

d1 = {'namelist': [{'name':"John",'age':23,'country':'USA'},
                   {'name':"Mary",'age':12,'country':'Italy'},
                   {'name':"Susan",'age':32,'country':'UK'}],
      'classteacher':'Jon Smith'}

for k1,v1 in d1.items():
    if isinstance(v1,list):
        for nb,d2 in enumerate(v1,1):
            for k2 in list(d2):
                d2[f'{k2}_{nb}'] = d2.pop(k2)

print(d1)
# {'namelist': [{'name_1': 'John', 'age_1': 23, 'country_1': 'USA'},
#               {'name_2': 'Mary', 'age_2': 12, 'country_2': 'Italy'},
#               {'name_3': 'Susan', 'age_3': 32, 'country_3': 'UK'}]}, 
#  'classteacher': 'Jon Smith'
# }

答案 4 :(得分:0)

您可以使用字典和列表推导:

d = {'namelist': [{'name': "John", 'age': 23, 'country': 'USA'},
              {'name': "Mary", 'age': 12, 'country': 'Italy'},
              {'name': "Susan", 'age': 32, 'country': 'UK'}]}
d = {k: [{'_'.join((n, str(i))): v for n, v in s.items()} for i, s in enumerate(l, 1)] for k, l in d.items()}

d将变为:

{'namelist': [{'name_1': 'John', 'age_1': 23, 'country_1': 'USA'}, {'name_2': 'Mary', 'age_2': 12, 'country_2': 'Italy'}, {'name_3': 'Susan', 'age_3': 32, 'country_3': 'UK'}]}

答案 5 :(得分:0)

for i, dct in enumerate(inp['namelist'], 1):
    for key, value in list(dct.items()):  # take a copy since we are modifying the dct
        del dct[key]  # delete old pair
        dct[key+'_'+str(i)] = value  # new key format

这将就位。您没有使用额外的内存。遍历dict中的每个值,然后删除旧的键值对,并在键名更改的情况下添加它。

答案 6 :(得分:0)

使用字典理解:

    mydictionary['namelist'] = [dict((key + '_' + str(i), value) for key,value in mydictionary['namelist'][i-1].items()) for i in [1, 2, 3]]