我有一个问题,我想确定我的方法是否合理。想法如下:
我将创建一个名为zip_code的主dict,其中相应的zipcodes(来自一个列表)是每个嵌套dict的名称。每个都有“成员”、“办公室”、“每个办公室的成员”的钥匙 它看起来是这样的:
zips {
90219: {
"members": 120,
"offices": 18,
"membersperoffice": 28
},
90220: {
"members": 423,
"offices": 37,
"membersperoffice": 16
}
}
以此类推。你知道吗
我认为我需要构建嵌套的dict,然后根据条件处理多个列表,将结果值动态地传递到相应的dict中(即,基于一个邮政编码在列表中存在的次数)。你知道吗
使用嵌套字典是最具python风格的方法吗?麻烦吗?有更好的办法吗?你知道吗
有人能给我一个提示,告诉我如何将键值从循环推送到嵌套的dict中吗?我还没有找到一个好的资源来描述我要做的事情(如果这确实是最好的方法的话)。你知道吗
谢谢。你知道吗
:edit:更具体的示例:
:编辑2:
MadPhysicast要求我给出代码示例(我甚至不知道从哪里开始,我找不到示例)。到目前为止我所能做的就是:
area_dict = {}
area_dict = dict.fromkeys(all_areas, 0) #make all of the zipscodes keys, add a zero in the first non-key index
dictkeys = list (area_dict.keys())
这给了我一个用一堆邮政编码作为钥匙的字典。我还没有发现遍历列表并创建嵌套dict的方法(目前还没有)。所以才是真正的问题。你知道吗
请不要把我塞进狗堆,做通常的堆溢出的事情。这不是我让任何人做作业。这只是我在请求别人给我一个暗示。你知道吗
:编辑3:
好的。这是令人费解的(我的错)。请允许我进一步澄清:
所以,我有一个例子说明嵌套的dict应该是什么样子。它们一开始是空的,但我需要遍历一个邮政编码列表来创建所有嵌套的dict。。。拉链里面。你知道吗
这是我想用来在zips dict中创建嵌套dict的列表示例:
zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]
这就是我想要的样子
zips {
90272: {
"members": ,
"offices": ,
"membersperoffice":
},
90049: {
"members": ,
"offices": ,
"membersperoffice":
}
}
。。。。 etc,etc(为列表中的每个zipcode创建相应的嵌套dict)
在我实现这一点之后,我必须遍历更多的邮政编码列表。。。这些数据将吐出一个邮政编码在给定列表中出现的次数,然后找到与所讨论的邮政编码对应的dict,并将该值附加到相关键。你知道吗
第一部分我自己想出来,第二部分我自己想出来。你知道吗
再次感谢。抱歉,有什么困惑。你知道吗
你可以这样做:
使用上述方法,如果
zipcode
多次出现在all_areas
列表中,则生成的zip
字典将只包含zipcode
的一个实例。你知道吗我建议做一个简单的对象来表示每个
zipcode
的值。一些简单的事情,比如:使用数据类:
使用命名元组:
然后可以将
code_members
函数更改为:举一个具体的例子:
我建议您在有实际值时附加它,而不是用每个键的空值初始化字典。你有一个键列表,我不明白你为什么要把所有的键都放在字典里而不是放在第一位。你知道吗
如果坚持用每个键的空值初始化
dict
,那么可以使用它,它也会在python
理解中遍历list
。你知道吗希望这有帮助
相关问题 更多 >
编程相关推荐