0

I have these dictionaries :

x={2020: 40, 2019: 37, 2015: 22, 2016: 9, 2017: 1}
y={2016: 0.0500, 2017: 0.0500, 2019: 0.0527, 2020: 0.0550, 2015: 0.0636}

and I want to obtain something like this :

data={2016:{9,0.0500},2017:{9,0.0500},2019:{37,0.0527},2020:{40,0.0550},2015:{22,0.0636}}

I want to have dict value inside my dict instead of list because I saw a way to do a graph like I want with that type of data.

I have found no clues on how to do it on internet right now, if you can help me a bit, thank you.

Thank you very much !

3 Answers3

2

Assuming x and y has same keys, you can do -

d = dict()
for k,v in x.items():
    d[k] = {v, y[k]}

print(d)

Though in this case every element of d is a set as dictionary will always have key, value pair.

Result:

{2020: {40, 0.055}, 2019: {0.0527, 37}, 2015: {0.0636, 22}, 2016: {0.05, 9}, 2017: {0.05, 1}}

kuro
  • 3,214
  • 3
  • 15
  • 31
  • It worked thank you very much ! but can you explain a bit what is a set ? – Enola Henrotin Apr 29 '21 at 08:54
  • Sets are one type of unordered data structure where every element is unique. Take a look at https://docs.python.org/3/tutorial/datastructures.html#sets – kuro Apr 29 '21 at 08:56
2

The format you want is not possible. Because {} signifies a dictionary but what you want is not dictionary. Rather you can use this

from collections import defaultdict
x = {2020: 40, 2019: 37, 2015: 22, 2016: 9, 2017: 1}
y = {2016: 0.0500, 2017: 0.0500, 2019: 0.0527, 2020: 0.0550, 2015: 0.0636}
dd = defaultdict(list)

for d in (x, y):
    for key, value in d.items():
        dd[key].append(value)
print(dd)
mhhabib
  • 2,975
  • 1
  • 15
  • 29
  • ah ? I thought it was possible because I saw it there : https://stackoverflow.com/questions/21822592/plot-a-scatter-plot-in-python-with-matplotlib-with-dictionary – Enola Henrotin Apr 29 '21 at 08:50
1
x = {2020: 40, 2019: 37, 2015: 22, 2016: 9, 2017: 1}
y = {2016: 0.0500, 2017: 0.0500, 2019: 0.0527, 2020: 0.0550, 2015: 0.0636}

result = {}
for k, v in x.items():
   for k1, v1 in y.items():
     if k == k1:
        result[k] = {v, v1}

print(result)

Output: {2020: {40, 0.055}, 2019: {0.0527, 37}, 2015: {0.0636, 22}, 2016: {0.05, 9}, 2017: {0.05, 1}}

66dibo
  • 19
  • 3