简体   繁体   中英

Convert Python dictionary to nested dictionary

I have a question concerning python dictionaries and nested dictionaries. If I had a dictionary like so:

data = {'abc': ['aaa', 'bbb', 'ccc'], 'def': ['ddd', 'eee', 'fff']}

Could I somehow convert the lists inside this dictionary to also be dictionaries? So that the output would be like:

data = {'abc': {'aaa', 'bbb', 'ccc'}, 'def': {'ddd', 'eee', 'fff'}}

I'm new to Python and just trying to understand nested dictionaries and how they work. Thank you in advance!

如果你想要一个集合字典,那么只需使用字典理解:

{key:set(value) for key,value in data.items()}

The syntax for a dict containing dicts would be

data = {
    'abc': {'aaa':1, 'bbb':2, 'ccc':42}, 
    'def': {'ddd':45, 'eee':"Monty", 'fff':None}, # this trailing comma is Pythonic
    }

What is in the question as asked is a dict containing sets, which is completely valid and useful.

You would use a dict containing sets (as opposed to lists) if your principal aim was to determine presence or absence, as in if 'aaa' in data['abc']: and specifically not to associate any values with the inner keys. (Before sets were added to Python, programmers used dicts with all values set to something arbitrary and irrelevant like 1 or None )

You would use a dict containing dicts if you want to be able to store values accessed by an outer and an inner key, as in data['aaa']['ddd'] = "I'm new here" , and you can of course still test if 'ddd' in data['aaa']:

data = {'abc': {'aaa', 'bbb', 'ccc'}, 'def': {'ddd', 'eee', 'fff'}}

is invalid python dictionary. Python dictionaries are in form of key:value pairs

What you currently have in your dictionary above is a dictionary of sets instead of dictionary of dictionaries.

What you could do is to add some 'dummy' keys to convert from list to dictionary. For example the following code:

data = {'abc': ['aaa', 'bbb', 'ccc'], 'def': ['ddd', 'eee', 'fff']}
dict2 = {}

i = 0
for key, value in data.items():
    dict2[key] = {}
    for element in value:
        dict2[key][i] = element
        i += 1
    i = 0

print dict2

will give you the following output (which is a nested dictionary):

{'abc': {0: 'aaa', 1: 'bbb', 2: 'ccc'}, 'def': {0: 'ddd', 1: 'eee', 2: 'fff'}}

Simply do this task using set :

data = {'abc': ['aaa', 'bbb', 'ccc'], 'def': ['ddd', 'eee', 'fff']}

b = {}
for key, value in data.items(): 
  b[key] = set(value)

print(b)

Output:

{'abc': {'ccc', 'bbb', 'aaa'}, 'def': {'fff', 'ddd', 'eee'}}

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