1

所以我想做的是改变字典函数有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']}
4

3 回答 3

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()}

……或者……</p>

dic = {name: Country(*value) for name, value in dic.items()}
于 2013-11-08T19:24:38.017 回答
2

你想要做的就是更新字典?

dict['canada'][1] = "150M+"

或者,使用嵌套字典,以便您可以编写:

dict['canada']['population'] = "150M+"
于 2013-11-08T19:13:35.977 回答
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

请注意,如果您使用字典或命名元组而不是列表作为字典中的值,这会容易得多。

于 2013-11-08T19:16:06.187 回答