有没有办法维护字典值的顺序?

Is there a way to maintain the order of dictionary values?

下面是我从元组列表中查找不同站点和不同名称的代码:

from collections import defaultdict,OrderedDict
weblogs = [
     ('Nanda', 'google.com'), ('Maha', 'google.com'), 
     ('Fei', 'python.org'), ('Maha', 'google.com'), 
     ('Fei', 'python.org'), ('Nanda', 'python.org'), 
     ('Fei', 'dzone.com'), ('Nanda', 'google.com'), 
     ('Maha', 'google.com'), ]
web = [t for t in (set(tuple(i) for i in weblogs))]
res = defaultdict(list)
for i, j in web:
    res[j].append(i)

a = OrderedDict()
a = dict(res)
for i,j in sorted(a.items()):
    print(i,j)

此输出在以下两个输出之间不断变化:

dzone.com ['Fei']
google.com ['Maha', 'Nanda']
python.org ['Nanda', 'Fei']

dzone.com ['Fei']
google.com ['Nanda', 'Maha']
python.org ['Fei', 'Nanda']

有没有办法保持值的固定顺序?

问题出在集合中值的顺序。一个简单的解决方案是更改该行:

web = [t for t in (set(tuple(i) for i in weblogs))]

像这样:

web = [t for t in (sorted(set(tuple(i) for i in weblogs)))]