{'Brazil': [19000000, 810000.00], 'Japan': [128000000, 350000.0]}
如果我有dict1
,其中包含有关国家/地区名称 ,人口和区域的数据,并且我想使用功能,以与当前词典相同的格式(其中的值包含在列表中)添加新国家/地区,人口和地区,我该怎么做?< / p>
答案 0 :(得分:2)
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]}
答案 1 :(得分:1)
请参见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]}
答案 2 :(得分:0)
pop = 10
area = 20
name = "A"
dict1[name] = [pop, area]
答案 3 :(得分:0)
dict1 = {}
def appendDict(country, population, area):
dict1[country] = [population, area]
appendDict("Brazil", "19000000", "810000.00")
appendDict("Japan", "128000000", "350000.0")
print(dict1)
答案 4 :(得分:0)
这是一个很好的例子:
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)