python,如何通过改变其格式来更新字典?

标签 python dictionary mutation

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

最佳答案

更好的数据结构将使这变得容易。例如,而不是这个:

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

关于python,如何通过改变其格式来更新字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19866783/

相关文章:

c++ - 带有 map 的部分类模板特化

dictionary - 不断向 map 添加数据

javascript - 从 contenteditable div 中获取已删除的节点(Froala Editor)

python - 在 SQLAlchemy 中使用 cdecimal

python - 如何为 pandas 条形图上的负值和正值着色?

iOS:将字典从 plist 文件加载到数组

c# - BitArray 改变范围内的位

object - 在 Dart-lang 中避免对象突变的方法有哪些?

python - 使用python列表理解根据条件查找元素的索引

python - 是否有一个 pandas 访问器来存储每个单元格中对象的底层值?