鏈的鍵一起,與列表理解,例如:
[v for key in yourdict for v in key]
如果你只需要遍歷,使用itertools.chain.from_iterable()
可以這樣做:
from itertools import chain
for v in chain.from_iterable(yourdict):
字典沒有排序,因此鍵的值也不會以任何特定順序(儘管每個鍵的2個值保持連續)。您可以隨時對它們進行排序:
sorted(v for key in yourdict for v in key)
或
sorted(chain.from_iterable(yourdict))
如果你不關心訂單,但不想重複,然後產生一組來代替:
{v for key in yourdict for v in key}
演示:
>>> yourdict = {(1, 2): 'a', (3, 4): 'b', (5, 6): 'c'}
>>> [v for key in yourdict for v in key]
[1, 2, 5, 6, 3, 4]
>>> from itertools import chain
>>> list(chain.from_iterable(yourdict))
[1, 2, 5, 6, 3, 4]
>>> sorted(v for key in yourdict for v in key)
[1, 2, 3, 4, 5, 6]
>>> sorted(chain.from_iterable(yourdict))
[1, 2, 3, 4, 5, 6]
而產生一組:
>>> anotherdict = {(1, 2): 'a', (3, 4): 'b', (4, 2): 'c'}
>>> {v for key in yourdict for v in key}
set([1, 2, 3, 4, 5, 6])
>>> {v for key in anotherdict for v in key}
set([1, 2, 3, 4])