繁体   English   中英

如何使用函数将新键和值附加到列表字典中

[英]How to append a new key and value into a dictionary of lists using a function

{'Brazil': [19000000, 810000.00], 'Japan': [128000000, 350000.0]}

如果我有dict1保存有关国家名称人口地区的数据,并且我想使用一个函数以与当前字典相同的格式添加新的国家、人口和地区(其中值包含在列表中) ,我该怎么做?

使用以下代码:

dict1 = {'Brazil': [19000000, 810000.00], 'Japan': [128000000, 350000.0]} #initial dict

def addToDict(c, p, a):
    #add new values to dict1, here we are adding country(c) as key, [population(p), area(a)] as value.
    dict1[c] = [p, a] #dict[c] = [p,a] <-- [p,a] are values assigned to the key identified-in/new-key in dict1
    return dict1      #optional - I used it just to see the final value.

print (addToDict('India', 1000000000, 10098978.778)) #main call

#result --> {'Brazil': [19000000, 810000.0], 'Japan': [128000000, 350000.0], 'India': [1000000000, 10098978.778]}

查看addNew函数:

dict1 = {'Brazil': [19000000, 810000.00], 'Japan': [128000000, 350000.0]}

def addNew(dict, country, population, area):
    dict.update({country: [population, area]})

addNew(dict1, 'countryTest', 200000, 1000.00)

print(dict1)

输出:

{'Brazil': [19000000, 810000.0], 'Japan': [128000000, 350000.0], 'countryTest': [200000, 1000.0]}
pop = 10
area = 20
name = "A"
dict1[name] = [pop, area]
dict1 = {}

def appendDict(country, population, area):
    dict1[country] = [population, area]

appendDict("Brazil", "19000000", "810000.00")
appendDict("Japan", "128000000", "350000.0")

print(dict1)

这是一个很好的例子:

travel_log = [
{
  "country": "France",
  "visits": 12,
  "cities": ["Paris", "Lille", "Dijon"]
},
{
  "country": "Germany",
  "visits": 5,
  "cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]

dict1 = {}
def add_new_country(country,visits,cities):
  dict1 = {}
  dict1['country']= country
  dict1['visits'] = visits
  dict1['cities'] = cities
  travel_log.append(dict1)

add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM