Python 如何在两个字典中压缩值

Python 如何在两个字典中压缩值,python,dictionary,zip,Python,Dictionary,Zip,我有两本字典: {('x0', '0'): 'x0', ('x0', '1'): 'x1', ('x1', '0'): 'x1', ('x1', '1'): 'x0'} 及 我想把它们压缩成这样,结果会是: {(('x0','y0'), 0) : ('x0','y1'), (('x0', 'y0'), 1) : ('x1, 'y1')... and so on} 实现这一目标的最佳方法是什么?我不太确定您的意图,但以下内容与您描述的内容类似: a = {('x0', '0'): 'x0',

我有两本字典:

{('x0', '0'): 'x0', ('x0', '1'): 'x1', ('x1', '0'): 'x1', ('x1', '1'): 'x0'}

我想把它们压缩成这样,结果会是:

{(('x0','y0'), 0) : ('x0','y1'), 
(('x0', 'y0'), 1) : ('x1, 'y1')... and so on}
实现这一目标的最佳方法是什么?

我不太确定您的意图,但以下内容与您描述的内容类似:

a = {('x0', '0'): 'x0', ('x0', '1'): 'x1', ('x1', '0'): 'x1', ('x1', '1'): 'x0'}
b = {('y0', '0'): 'y1', ('y0', '1'): 'y1', ('y1', '0'): 'y0', ('y1', '1'): 'y0'}
{((x[0], y[0]), x[1]): (a[x], b[y]) for x, y in zip(a.keys(), b.keys())}
>> {(('x0', 'y0'), '0'): ('x0', 'y1'), (('x0', 'y0'), '1'): ('x1', 'y1'), (('x1', 'y1'), '0'): ('x1', 'y0'), (('x1', 'y1'), '1'): ('x0', 'y0')}

在Python3.7中,字典是有序的,因此,您可以迭代
dict.items()

输出:

{(('x0', 'y0'), '0'): ('x0', 'y1'), (('x0', 'y0'), '1'): ('x1', 'y1'), (('x1', 'y1'), '0'): ('x1', 'y0'), (('x1', 'y1'), '1'): ('x0', 'y0')}

但是,此解决方案只能在Python3.7中使用。考虑到使用任何其他版本,考虑使用<代码>集合.OrrordEddit < /C>或将该结构作为元组列表来确保始终发生适当的配对。在Python 3.7之前,

> AJAX1234,<代码> DICT.Test< <代码>没有排序,但这并不意味着您不能自己排序!p> 确认它是无序的(Python 3.5)

显式排序

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'))]
创建新的
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')}
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'))]
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'))]
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')}