织梦CMS - 轻松建站从此开始!

abg欧博官网|登陆|游戏|

How to zip values in two dictionaries

时间:2026-01-12 19:09来源: 作者:admin 点击: 0 次
As @Ajax1234 mentioned, before Python 3.7, dict.items isn't ordered, but that doesn't mean you can't sort it yourself! Confirming that it's unordered

As @Ajax1234 mentioned, before Python 3.7, dict.items isn't ordered, but that doesn't mean you can't sort it yourself!

Confirming that it's unordered (Python 3.5)

In [132]: list(zip(x.items(), y.items())) Out[132]: [((('x0', '0'), 'x0'), (('y0', '1'), 'y1')), ((('x1', '0'), 'x1'), (('y1', '0'), 'y0')), ((('x0', '1'), 'x1'), (('y0', '0'), 'y1')), ((('x1', '1'), 'x0'), (('y1', '1'), 'y0'))]

Explicitly ordering it

In [129]: list(zip(sorted(x.items()), sorted(y.items()))) Out[129]: [((('x0', '0'), 'x0'), (('y0', '0'), 'y1')), ((('x0', '1'), 'x1'), (('y0', '1'), 'y1')), ((('x1', '0'), 'x1'), (('y1', '0'), 'y0')), ((('x1', '1'), 'x0'), (('y1', '1'), 'y0'))]

Creating your new dict

In [131]: {((x0, y0), x1): (x, y) for ((x0, x1), x), ((y0, y1), y) in zip(sorted(x.items()), sorted(y.items()))} Out[131]: {(('x0', 'y0'), '0'): ('x0', 'y1'), (('x0', 'y0'), '1'): ('x1', 'y1'), (('x1', 'y1'), '0'): ('x1', 'y0'), (('x1', 'y1'), '1'): ('x0', 'y0')}

(责任编辑:)
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:
发布者资料
查看详细资料 发送留言 加为好友 用户等级: 注册时间:2026-01-13 07:01 最后登录:2026-01-13 07:01
栏目列表
推荐内容