简体   繁体   English

将列表项迭代到嵌套字典中的大多数pythonic方法

[英]Most pythonic way of iterating list items into a nested dict

I have a problem and I want to determine whether my approach is sound. 我有一个问题,我想确定我的方法是否正确。 Here is the idea: 这里是想法:

I would be creating a primary dict called zip_codes, of which respective zipcodes (from a list) were the names of each of the nested dicts. 我将创建一个名为zip_codes的主字典,其中每个邮政编码(从列表中)是每个嵌套字典的名称。 Each would have keys for "members", "offices", "members per office" It would look like this: 每个都有“成员”,“办公室”,“每个办公室的成员”的键。它看起来像这样:

zips {
    90219: {
      "members": 120,
      "offices": 18,
      "membersperoffice": 28
    },
    90220: {
      "members": 423,
      "offices": 37,
      "membersperoffice": 16
    }
}

and so on and so forth. 等等等等。

I think I need to build the nested dicts, and then process several lists against conditionals, passing resulting values into the corresponding dicts on the fly (ie based on how many times a zip code exists in the list). 我想我需要构建嵌套的字典,然后根据条件处理多个列表,将结果值即时传递给相应的字典(即,基于列表中邮政编码的数量)。

Is using nested dictionaries the most pythonic way of doing this? 使用嵌套字典是执行此操作的最有效的方法吗? Is it cumbersome? 麻烦吗? Is there a better way? 有没有更好的办法?

Can someone drop me a hint about how to push key values into nested dicts from a loop? 有人可以给我一个关于如何将关键值从循环中推入嵌套字典的提示吗? I've not been able to find a good resource describing what I'm trying to do (if this is, indeed, the best path). 我找不到能够描述我要做什么的好资源(如果确实是最佳途径)。

Thanks. 谢谢。

:edit: a more specific example: :edit:一个更具体的例子:

  1. determine how many instances of a zipcode are in list called membersperzip 确定列表中有多少个邮政编码实例称为membersperzip
  2. find corresponding nested dict with same name as zipcode, inside dict called zips 在名为zips的字典中找到与邮政编码相同名称的对应嵌套字典
  3. pass value to corresponding key, called "members" (or whatever key) 将值传递给相应的键,称为“成员”(或任何键)

:edit 2: :编辑2:

MadPhysicist requested I give code examples (I don't even know where to start with this one and I can't find examples. All I've been able to do thus far is: MadPhysicist请求我提供代码示例(我什至不知道从哪里开始,也找不到示例。到目前为止,我所能做的就是:

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())

That gets me a dict with a bunch of zip codes as keys. 这使我成为了以一堆邮政编码作为键的字典。 I've discovered no way to iterate through a list and create nested dicts (yet). 我发现没有办法遍历列表并创建嵌套字典(尚未)。 Hence the actual question. 因此,实际的问题。

Please don't dogpile me and do the usual stack overflow thing. 请不要dog我,并执行通常的堆栈溢出操作。 This is not me asking anyone to do my homework. 这不是我要任何人做作业。 This is merely me asking someone to drop me a HINT. 这仅仅是我要某人给我的提示。

:edit 3: :编辑3:

Ok. 好。 This is convoluted (my fault). 这令人费解(我的错)。 Allow me to clarify further: 请允许我进一步说明:

So, I have an example of what the nested dicts should look like. 因此,我有一个嵌套字典应该是什么样子的示例。 They'll start out empty, but I need to iterate through one of the zip code lists to create all the nested dicts... inside of zips. 他们将开始是空的,但我需要遍历一个邮政编码列表以创建所有嵌套的字典……在zip内。

This is a sample of the list that I want to use to create the nested dicts inside of the zips dict: 这是我想用于在zip字典内部创建嵌套字典的列表的示例:

zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]

And this is what I want it to look like 这就是我想要的样子

zips {
    90272: {
      "members": ,
      "offices": ,
      "membersperoffice": 
    },
    90049: {
      "members": ,
      "offices": ,
      "membersperoffice": 
    }
}

.... etc, etc. ( creating a corresponding nested dict for each zipcode in the list) ....等等,等等(为列表中的每个邮政编码创建一个对应的嵌套字典)

After I achieve this, I have to iterate through several more zip code lists... and those would spit out the number of times a zip code appears in a given list, and then find the dict corresponding to the zip code in question, and append that value to the relevant key. 完成此操作后,我必须遍历其他几个邮政编码列表……这些列表会吐出邮政编码出现在给定列表中的次数,然后找到与该邮政编码对应的字典,然后将该值附加到相关密钥。

One I figure out the first part, I can figure this second part out on my own. 我想出第一部分,我可以自己解决第二部分。

Thanks again. 再次感谢。 Sorry for any confusion. 抱歉给您带来任何混乱。

You can do something like this: 您可以执行以下操作:

all_areas = [90219, 90220]

zips = {zipcode: code_members(zipcode) for zipcode in all_areas}

def code_members(zipcode):
    if zipcode == 90219:
        return dict(members=120, offices=18, membersperoffice=28)
    return dict(members=423, offices=37, membersperoffice=16)

I think I need to build the nested dicts, and then process several lists against conditionals, passing resulting values into the corresponding dicts on the fly ( ie based on how many times a zip code exists in the list ). 我想我需要构建嵌套的字典,然后根据条件处理多个列表,将结果值即时传递给相应的字典( 即,基于列表中邮政编码的数量 )。

Using the above approach, if a zipcode appears multiple times in the all_areas list, the resulting zip dictionary will only contain one instance of the zipcode . 使用上述方法,如果zipcodeall_areas列表中多次出现,则生成的zip字典将仅包含zipcode一个实例。

Is using nested dictionaries the most pythonic way of doing this? 使用嵌套字典是执行此操作的最有效的方法吗? Is it cumbersome? 麻烦吗? Is there a better way? 有没有更好的办法?

May I suggest making a simple object that represents the value of each zipcode . 我可以建议创建一个简单的对象来表示每个zipcode的值。 Something simple like: 很简单的东西:

Using dataclass: 使用数据类:

@dataclass.dataclass
class ZipProperties(object):
    members: int
    offices: int
    membersperoffice: int

Using named tuple: 使用命名元组:

ZipProperties = collections.namedtuple('ZipProperties', ['members', 'offices', 'membersperoffice'])

You can then change the code_members function to this: 然后,您可以将code_members函数更改为此:

def code_members(zipcode):
    if zipcode == 90219:
        return ZipProperties(120, 18, 28)
    return ZipProperties(423, 37, 16)

Addressing your concrete example: 解决您的具体示例:

  1. determine how many instances of a zipcode are in list called membersperzip 确定列表中有多少个邮政编码实例称为membersperzip
  2. find corresponding nested dict with same name as zipcode, inside dict called zips 在名为zips的字典中找到与邮政编码相同名称的对应嵌套字典
  3. pass value to corresponding key, called "members" (or whatever key) 将值传递给相应的键,称为“成员”(或任何键)
membersperzip: typings.List[Tuple[int, int]] = [(90219, 54)]

for zip, members in membersperzip:
    for zipcode, props in zips.items():
        if zipcode == zip:
            props.members = members

I would suggest you to append it when you have the actual value instead of initializing dictionary with empty values for each key. 我建议您在有实际值时附加它,而不是用每个键的空值初始化字典。 You have list of keys and I do not see why you want to put all of them to the dictionary without having value in the first place. 您有键的列表,但我不明白为什么要把所有键都放在字典中而不首先放在值上。

zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]
zips_dict = {}
for a_zip in zips:
    if a_zip not in zips_dict:
        # Initialize proper value here for members etc.
        zips_dict[a_zip] = proper_value

If you insist to initialize dict with empty value for each keys, you could use this, which will also iterate through the list anyway but in python comprehension. 如果您坚持使用每个键的空值来初始化dict ,则可以使用此方法,无论如何,它都会在python理解中迭代list

zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]
zips_dict = {
   x:{
       "members":None,
       "offices":None,
       "membersperoffice":None,
   } for x in zips
}

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python编码嵌套在dict中的列表项的方法 - Pythonic way to encode list items nested in dict 初始化字典的大多数pythonic方法 - Most pythonic way to initialize a dict 使用列表值对 dict 进行排序的最pythonic方法是什么? - What is the most pythonic way to sort a dict with list values? 从 OrderedDict 列表中查找项目的最pythonic 方法是什么? - what would be the most pythonic way of finding items from a list of OrderedDict? 大多数Pythonic方法在O(1)复杂度的列表中查找/检查项目? - Most Pythonic way to find/check items in a list with O(1) complexity? 获得有序的独特项目列表的最佳/最pythonic方式 - Best / most pythonic way to get an ordered list of unique items 确保对象列表的大多数pythonic方法仅包含唯一项 - Most pythonic way of ensuring a list of objects contains only unique items 将 function 应用于列表的某些项目的最pythonic方法是什么? - What is the most pythonic way to apply function to some items of a list? 将列表的字典转换为字典中所有元素的所有组合的字典列表的最有效方法? - Most pythonic way to convert a dict of lists into a list of dicts of all combs of the elements in the lists from the dict? 处理嵌套字典列表的最 Pythonic 方法是什么? - What's the most Pythonic way to deal with a list of nested dictionaries?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM