所以我想做的是改变词典
该函数有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']}
答案 0 :(得分:3)
更好的数据结构会让这很容易。例如,而不是:
{country_name: [location, population, president]}
...让我们说你有这个:
{country_name:
{'location': location, 'population': population, 'president': president}}
然后你的功能就是:
def mutate_dic(dic, country_name, field, new_data):
dic[country_name][field] = new_data
虽然真的,在这种情况下,该功能只是混淆了一些事情。哪个更明显?
dic['canada']['population'] = '150M+'
mutate_dic(dic, 'canada', 'population', '150+')
如果你有一个Country
课程,那么你可以做得更好 - 当有一个简短的静态字段列表时,为什么不让它们成为属性呢?
class Country(object):
def __init__(self, location, population, president='none'):
self.location = location
self.population = population
self.president = president
dic = {'canada': Country('North America', '150M+')}
dic['canada'].population = '100M+'
无论哪种方式,您都可以将数据文件直接读取为其中一种格式。由于你没有向我们展示文件,我会做一个,并说明如何阅读:
数据文件:
name,location,population,president
Canada,North America,100M+,none
France,Europe,65.7M,Hollande
脚本:
import csv
with open('datafile', 'rb') as f:
reader = csv.DictReader(f)
dic = {row['name'].lower(): row for row in reader}
print dic
输出:
{'canada': {'location': 'North America',
'name': 'Canada',
'population': '100M+',
'president': 'none'},
'france': {'location': 'Europe',
'name': 'France',
'population': '65.7M',
'president': 'Hollande'}}
但如果最糟糕的情况发生,你可以在输入后始终从一种格式转换为另一种格式:
dic = {name: {'location': value[0], 'population': value[1], 'president': value[2]}
for name, value in dic.items()}
......或......
dic = {name: Country(*value) for name, value in dic.items()}
答案 1 :(得分:2)
你想要做的就是更新字典吗?
dict['canada'][1] = "150M+"
或者,使用嵌套字典,以便您可以写:
dict['canada']['population'] = "150M+"
答案 2 :(得分:2)
以下内容应该有效:
def mutate_dic(dic, country_name, field, new_data):
field_indices = {'location': 0, 'population': 1, 'president': 2}
dic[country_name][field_indices[field]] = new_data
要将其分解为更多步骤,以便更容易理解:
list_to_change = dic[country_name]
index_of_field = field_indices[field]
list_to_change[index_of_field] = new_data
请注意,如果您使用字典或命名元组而不是列表作为字典中的值,则会更容易。