Quantcast
Channel: User martineau - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by martineau for Create a nested dictionary with multipe dictionaries

$
0
0

I also think that using dictionary comprehensions is the best way to to solve this problem — but think it can be done in a more readable and flexible manner, like so:

countries = {'Portugal', 'US'}score = {'Portugal': 88.0, 'US': 86.20}year = {'Portugal': 2014, 'US': 2013}price = {'Portugal': 26.77, 'US': 36.58}# Map variable names to corresponding data dictionaries.dicts = {name: globals()[name] for name in ("score", "year", "price")}# Pull data out for each country.dd = {country:        {name: data[country] for name, data in dicts.items()}            for country in countries}from pprint import pprintpprint(dd, sort_dicts=False)

Output:

{'Portugal': {'score': 88.0, 'year': 2014, 'price': 26.77},'US': {'score': 86.2, 'year': 2013, 'price': 36.58}}

Viewing all articles
Browse latest Browse all 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>