简体   繁体   中英

create dict from other dicts with for loop in python

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.

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()))

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