简体   繁体   中英

Transform dict into 2 key dict

I have a dictionary that looks like the below:

{'AL': {'FL': 1, 'GA': 0, 'MS': 0, 'TN': 0},
'AR': {'LA': 0, 'MO': 0, 'MS': 0, 'OK': 0, 'TN': 16, 'TX': 0}
...}

I'd like transform it to a two key-pair dictionary.

FlowDict[('AL','FL')] returns {('AL','FL'): 1)}

I saw this on another stack and tried to implement it as follows: {i.pop('AL'): i for i in FlowDict} . But I don't think this is the direction I need to go. Appreciate any help.

A nested dictionary comprehension comes in handy here:

>>> FlowDict = {(key1,key2):value for key1 in d for key2,value in d[key1].items()}
>>> FlowDict
{('AL', 'FL'): 1,
 ('AL', 'GA'): 0,
 ('AL', 'MS'): 0,
 ('AL', 'TN'): 0,
 ('AR', 'LA'): 0,
 ('AR', 'MO'): 0,
 ('AR', 'MS'): 0,
 ('AR', 'OK'): 0,
 ('AR', 'TN'): 16,
 ('AR', 'TX'): 0}

What you have in your question won't quite work. That will just merge dicts.

A nested dictionary comprehension, however, will work for you:

test = {'AL': {'FL': 1, 'GA': 0, 'MS': 0, 'TN': 0},
'AR': {'LA': 0, 'MO': 0, 'MS': 0, 'OK': 0, 'TN': 16, 'TX': 0}}

flattened = {(main_key, sub_key): value for main_key, sub_dict in test.items() for sub_key, value in sub_dict.items()}
print(flattened)

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