简体   繁体   English

从列表创建嵌套字典

[英]Creating a nested dictionary from a list

I have a list Final_Bioteck whose first 5 enteries looks like this: 我有一个Final_Bioteck列表,其前5个Final_Bioteck看起来像这样:

['PBYI', 'DRRX', 'FBIO', 'CAPR', 'KDMN']

I'm trying to create a nested dictionary with the first layer being the letters of the alphabet and the second layer being an element from the above list. 我正在尝试创建一个嵌套的字典,第一层是字母,第二层是上述列表中的元素。 I'm trying to create an indexed dictionary. 我正在尝试创建索引字典。

I attempted to do so with the code below: 我尝试使用以下代码进行操作:

from string import ascii_uppercase

Bioteck_dict ={}
for letter in ascii_uppercase:
    for stock in Final_Bioteck:
        if stock.startswith(letter):
            try:
                Bioteck_dict[letter].update(stock)
            except KeyError:
                Bioteck_dict[letter] = stock

However, I'm getting the following error: 但是,出现以下错误:

'str' object has no attribute 'update'

Desired output is something like this: 所需的输出是这样的:

Bioteck_dict Bioteck_dict

{A:
B:
C: 'CAPR':{}
D:  'DRRX':{}
E:
F:

or even this: 甚至这个:

 {A:
    B:
    C: 'CAPR'
    D:  'DRRX'
    E:
    F:   'FBIO':


              }

.update() is a method for dicts, and you're calling it on a string. .update()是用于.update()的方法,您可以在字符串上调用它。 This is a way of doing what you appear to want: 这是一种执行您想要的操作的方法:

Final_Bioteck = ['PBYI', 'DRRX', 'FBIO', 'CAPR', 'KDMN']
Bioteck_dict = {}
for stock in Final_Bioteck:
    Bioteck_dict.setdefault(stock[0], {})[stock] = {}

Following the update to your question, it seems like you want letters that have no associated stocks to nonetheless be explicitly represented in the dict as empty containers. 在对问题进行更新之后,您似乎希望将没有关联库存的信件在dict明确表示为空容器。 It's questionable whether you really need that (most things you would subsequently want to do will involve just iterating over what is in the dict ) but you can get that effect in one of two ways: 这是值得怀疑是否真的需要(大多数事情,你会随后想做将只涉及迭代什么在dict ),但你可以在以下两种方式之一是效果:

EITHER: 等等:

Final_Bioteck = ['PBYI', 'DRRX', 'FBIO', 'CAPR', 'KDMN']
from collections import defaultdict
Bioteck_dict = defaultdict(dict)   # now you can look up any letter (or any key at all) and receive the empty dict, even if there was no entry there before
for stock in Final_Bioteck:
    Bioteck_dict[stock[0]][stock] = {}

OR: 要么:

Final_Bioteck = ['PBYI', 'DRRX', 'FBIO', 'CAPR', 'KDMN']
Bioteck_dict = {letter:{} for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
for stock in Final_Bioteck:
    Bioteck_dict[stock[0]][stock] = {}

The problem is that you're assigning each dict value as a string, not a dict. 问题是您要将每个字典值分配为字符串,而不是字典。 It needs to start off as a dict so you can update it. 它需要作为命令开始,以便您可以对其进行更新。 'FBIO'.update(blah) makes no sense. 'FBIO'.update(blah)没有意义。 Additionally, you probably want a dict of lists, rather than a dict of dicts—what would the key be, after all? 此外,您可能想要列表的字典,而不是字典的字典-关键是什么?

from collections import defaultdict

Bioteck_dict = defaultdict(list)  # Or `set`, if unique and unordered.
for stock in Final_Bioteck:
    Bioteck_dict[stock[0]].append(stock)

The result is: 结果是:

{'C': ['CAPR'], 'D': ['DRRX'], 'F': ['FBIO'], 'K': ['KDMN'], 'P': ['PBYI']}

This one is a bit more akin to your logic: 这有点类似于您的逻辑:

from string import ascii_uppercase

stocks = ['PBYI', 'DRRX', 'FBIO', 'CAPR', 'KDMN']
d = {}
for letter in ascii_uppercase:
    d[letter] = {}
    for stock in stocks:
        if stock.startswith(letter):
            d[letter][stock] = {}

print d

That returns: 返回:

{'A': {}, 'C': {'CAPR': {}}, 'B': {}, 'E': {}, 'D': {'DRRX': {}}, 'G': {}, 'F': {'FBIO': {}}, 'I': {}, 'H': {}, 'K': {'KDMN': {}}, 'J': {}, 'M': {}, 'L': {}, 'O': {}, 'N': {}, 'Q': {}, 'P': {'PBYI': {}}, 'S': {}, 'R': {}, 'U': {}, 'T': {}, 'W': {}, 'V': {}, 'Y': {}, 'X': {}, 'Z': {}}

Using dict comprehension, if unique records. 如果有唯一记录,则使用dict理解。

l = ['PBYI', 'DRRX', 'FBIO', 'CAPR', 'KDMN']
d = { i[0]:i for i in l}
pprint(d)

Output: 输出:

{'C': 'CAPR', 'D': 'DRRX', 'F': 'FBIO', 'K': 'KDMN', 'P': 'PBYI'}

Use defaultdict if multiple records. 如果有多个记录,请使用defaultdict。

l = ['PBYI', 'DRRX', 'FBIO', 'CAPR', 'KDMN', 'DUMMY','CAT','COLD']
from collections import defaultdict
d = defaultdict(list)
for i in l:
    d[i[0]].append(i)
pprint(d)

Output: 输出:

defaultdict(<class 'list'>,
            {'C': ['CAPR', 'CAT', 'COLD'],
             'D': ['DRRX', 'DUMMY'],
             'F': ['FBIO'],
             'K': ['KDMN'],
             'P': ['PBYI']})

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM