在Python中更新字典词典 [英] Updating Dictionary of Dictionaries in Python
问题描述
%d是一个从dictReader = csv.DictReader(placesFile)获得的迭代器
%定义我的命令名为place
places = {City:{},Country:{}}
然后我尝试将新对象添加到我的dict命令中,如下所示,但这似乎没有工作。有没有办法做到这一点?在dictReader中的
new_City = city_constructor(d [人口 ],d [Area])
places.update({City:new_City})
您应该可以更新您的地方
字典:
place [City] = new_City
如果你的文件在每一行都有City信息,那么我猜你会在做$ code> new_City = city_constructor(d [Population],d [Area])在每一行。在这种情况下,您的位置
应该如下所示:
places = { City:[],Country:[]}
for d在dictReader中:
new_City = city_constructor(d [人口],d [区域] )
place [City]。append(new_City)
如果必须一个简单的例子,那么你的地方
应该是这样的:
{
City:{
City_1:< city_constructor(d [人口],d [区域])第一行>
City_2 < city_constructor(d [Population],d [Area])第二行>
City_3:< city_constructor(d [Population],d [Area])第三行>
}
}
就是说,与一个新城市遇到的每一行相关联的新密钥。可能是这样的:
count = 0
for d在dictReader中:
new_City = city_constructor d [人口],d [区域])
_a_dict = {'City _ {}'。format(count):new_City}
count + = 1
places [City ] .update(_a_dict)
I'm essentially reading in a CSV File and am creating an Object called "City" which is created using attributes passed to the constructor "city_constructor". Edit: The file has "City" information on every line. I have a dict of dicts which I am struggling to update, which takes in key values associated with 2 different Classes:
% d is an iterator obtained from dictReader = csv.DictReader(placesFile)
% Defining my dict of dicts called places
places = {"City":{}, "Country":{}}
And I then try and add the new object into my dict of dicts as follows, but this does not appear to be working. Is there a way to do this?:
for d in dictReader:
new_City = city_constructor(d["Population"],d["Area"])
places.update({"City":new_City})
You should be able to update your places
dictionary with:
places["City"] = new_City
If your file has "City" information on every line, then I am guessing you would be doing new_City = city_constructor(d["Population"],d["Area"])
on every line. In that case, your places
should be like:
places = {"City":[], "Country":[]}
And you would update it as:
for d in dictReader:
new_City = city_constructor(d["Population"],d["Area"])
places["City"].append(new_City)
If it has to be a dict of dicts, then your places
should be structured something like:
{
"City": {
"City_1": <city_constructor(d["Population"],d["Area"]) of first line>,
"City_2": <city_constructor(d["Population"],d["Area"]) of second line>,
"City_3": <city_constructor(d["Population"],d["Area"]) of third line>,
}
}
That is, there has to be a new key associated with every line a new city is encountered. May be something like this:
count = 0
for d in dictReader:
new_City = city_constructor(d["Population"],d["Area"])
_a_dict = {'City_{}'.format(count):new_City}
count += 1
places["City"].update(_a_dict)
这篇关于在Python中更新字典词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!