更好的数据结构将使这变得容易。例如,而不是这个:
{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()}
……或者……</p>
dic = {name: Country(*value) for name, value in dic.items()}