简体   繁体   中英

Is there a better way to query value in a dict with the key which is value in another dict?

I have multiple dict.

package_sender_map = {'package_1': 'vici'}
sender_level_map = {'vici': 'level_3', 'Jone': 'level_1'}
level_ability_map = {'level_1': '30', 'level_2': '50', 'level_3': '100'}

Now I want to get a package's sender's ability. The only way I find out is :

level_ability_map.get(sender_level_map.get(package_sender_map.get('package_1')))

It looks too long and hard to understand. Is there a simple and clear way to make relationship with multiple dicts?

You can make a stack of your dicts by putting them into a list (or tuple), and then loop over the stack. Like this:

package_sender_map = {'package_1': 'vici'}
sender_level_map = {'vici': 'level_3', 'Jone': 'level_1'}
level_ability_map = {'level_1': '30', 'level_2': '50', 'level_3': '100'}

dict_stack = [package_sender_map, sender_level_map, level_ability_map]
v = 'package_1'
for d in dict_stack:
    v = d[v]
print(v)

output

100 

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