|
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')} (责任编辑:) |
