简体   繁体   中英

Creating a nested dictionary from a list

I have a list Final_Bioteck whose first 5 enteries looks like this:

['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

{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. 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. 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:

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. 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.

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.

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']})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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