[英]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.