【发布时间】:2013-11-20 22:03:21
【问题描述】:
所以我想做的是改变字典
该函数有4个参数
格式为{country_name:[location, population, president]}
def mutate dic(dic_format, country_name, field, new_data):
dic_format = {country_name:['location', 'population', 'president']}
if field == 'location':
dic_format[:] = {country_name:[val, 'population', 'president']}
elif field == 'population':
dic_format[:] = {country_name:['location', val, 'president']}
elif field == 'president':
dic_format[:] = {country_name:['location', 'population', val]}
这是我正在考虑的,我知道它不起作用。 我该怎么做才能得到这样的输出:
>>>dict = {'canada':['North_America', '100M+', 'none']}
>>>mutate_dic(dict, 'canada', 'population', '150M+')
>>>dict
{'canada':['North_America', '150M+', 'none']}
【问题讨论】:
-
为什么不使用字典作为主字典中的值?无论如何,如果您需要订购这些值,请使用
collections.OrderedDict。喜欢:my_dict = {'canada': {'population':'100M+'}}然后你可以这样做:my_dict['canada']['population'] = '150M+' -
“使用字典作为主字典中的值”是什么意思?
-
@user2924679:评论中有一个例子。
-
这种格式是由某些要求或其他代码强加给您的吗?您认为可能必须使用的东西,因为您无法想象任何其他方式,例如读取 CSV 文件;还是您只是无缘无故选择并且可以轻松更改的东西?
-
@abarnert 是的,我需要打开一个文件并阅读它。并使用格式作为文件中给出的内容
标签: python dictionary mutation