在Python中更新字典词典

时间:2014-09-19 00:15:58

标签: python dictionary

我实际上是在读取CSV文件并创建一个名为“City”的对象,该对象是使用传递给构造函数“city_constructor”的属性创建的。 编辑:文件每行都有“城市”信息。我有一个dicts的词典,我正在努力更新,它接受与2个不同类相关的键值:

% d is an iterator obtained from dictReader = csv.DictReader(placesFile)
% Defining my dict of dicts called places
places = {"City":{}, "Country":{}}

然后我尝试将新对象添加到我的dicts字典中,如下所示,但这似乎不起作用。有没有办法做到这一点?:

for d in dictReader:
    new_City = city_constructor(d["Population"],d["Area"])
    places.update({"City":new_City})

3 个答案:

答案 0 :(得分:2)

您应该能够使用以下内容更新places字典

places["City"] = new_City

如果您的文件有" City"关于每一行的信息,那么我猜你会在每一行都做new_City = city_constructor(d["Population"],d["Area"])。在这种情况下,您的places应该是:

places = {"City":[], "Country":[]}

您可以将其更新为:

for d in dictReader:
    new_City = city_constructor(d["Population"],d["Area"])
    places["City"].append(new_City)

如果它必须是dicts的词典,那么你的places应该是这样的结构:

{
    "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>,
    }
}

也就是说,必须有一个与新城市遇到的每一行相关联的新密钥。可能是这样的:

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)

答案 1 :(得分:1)

要更新单个密钥,您应该使用此代码:

places["City"] = new_City

答案 2 :(得分:1)

for d in dictReader:
    new_City = city_constructor(d["Population"],d["Area"])
    try:
        places["City"].append(new_City)
    except KeyError:
        places["City"] = [new_City]

至少我认为......假设我理解你的要求