-2

What is a good way to get different dictionaries from already existing dictionaries?

For example i have this:

x = {"x1":1,"x2":2,"x3":3}
y = {"y1":1,"y2":2,"y3":3}
z = {"z1":1,"z2":2,"z3":3}

And i want this:

dict1 = {"x1":1,"y1":1,"z1":1}
dict2 = {"x2":2,"y2":2,"z2":2}
dict3 = {"x3":3,"y3":3,"z3":3}

Assuming i have more data than that, i want an efficient fast method like a loop.

  • 2
    Do you need to transpose or something else, the output is confusing. – anik jha Jan 02 '21 at 23:12
  • 3
    Do you know dictionaries are unordered ? – Moinuddin Quadri Jan 02 '21 at 23:14
  • No i just want to have evry first, second and third value of evry dict in new dicts. – DarkHackerxXx Jan 02 '21 at 23:15
  • look at this question https://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values – ori ofek Jan 02 '21 at 23:17
  • yes, in my case i have lab data in dicts online = {"on1":Ondata1,"on2":Ondata2,"on3":Ondata3} and offline = {"off1":Offdata1,"off2":Offdata2,"off3":Offdata3} for online and offline measured values. Out of that i want to make experiment dicts, exp1 = {on1":Ondata1, "off1":Offdata1} and so on – DarkHackerxXx Jan 02 '21 at 23:20
  • 1
    I think dictionary is not the best data struct for this problem. Dictionaries are unordered. I would store the values in arrays `xs = [1, 2, 3]`, `ys=[2,3,2] `... concatenate them, take transpose and read the rows again.... – mandulaj Jan 02 '21 at 23:20

1 Answers1

1

You can use zip to achive this -

a, b, c = [i for i in zip(x.items(), y.items(), z.items())]
dict1, dict2, dict3 = dict(a), dict(b), dict(c)

print(dict1)
print(dict2)
print(dict3)
{'x1': 1, 'y1': 1, 'z1': 1}
{'x2': 2, 'y2': 2, 'z2': 2}
{'x3': 3, 'y3': 3, 'z3': 3}

EDIT: As @Moinuddin rightly pointed out, you could write it in one line by mapping the type conversion to the zip object.

dict1, dict2, dict3 = map(dict, zip(x.items(), y.items(), z.items()))
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
  • 2
    Also it's worth mentioning that dictionary maintain the insertion order since Python 3.7. Before that dictionaries were unordered – Moinuddin Quadri Jan 02 '21 at 23:31