【问题标题】:nested Dictionary print differently after sorting by inner dictionary values in python嵌套字典在python中按内部字典值排序后打印不同
【发布时间】:2021-12-02 13:04:49
【问题描述】:

我正在尝试按内部字典的值对嵌套字典进行排序。分拣很顺利。但是当我检查我的结果时,我发现当我只使用变量 (d2) 时打印了原始 dict,但是当我使用 print(d2) 时它给了我正确的结果

d2 = {1: {1: 4, 2: 5, 3: 6}, 
      2: {7: 13, 8: 14, 9: 15, 10: 16, 11: 17, 12: 18},
      3: {1: 1, 2: 9, 3: 4}}

# sorting by inner dict value
for keys in d2.keys():
  sorted_tuples = sorted(d2[keys].items(), key=operator.itemgetter(1), reverse=True)
  d2[keys] = {k: v for k, v in sorted_tuples}

print(d2)
d2

{1: {3: 6, 2: 5, 1: 4}, 2: {12: 18, 11: 17, 10: 16, 9: 15, 8: 14, 7: 13}, 3: {2: 9, 3: 4, 1: 1}}
{1: {1: 4, 2: 5, 3: 6},
 2: {7: 13, 8: 14, 9: 15, 10: 16, 11: 17, 12: 18},
 3: {1: 1, 2: 9, 3: 4}}

为什么当我使用 d2 和 print(d2) 时输出不同

【问题讨论】:

  • 你在什么环境下编码?

标签: python dictionary nested


【解决方案1】:

朋友!有没有用漂亮的打印模块打印d2的结果?我只能使用漂亮的打印模块来复制你的行为。 Pretty print 在打印字典之前按字母顺序对字典进行排序,可以是disabled

我最初(并且错误地)怀疑d2print(d2) 之间的不同输出是由于字典是无序数据集合的结果;我怀疑dict.__str__dict.__repr__ 的差异已经足够大了。如果您希望保持其顺序,我建议您在标准字典上使用OrderedDict --despite Python preserving dictionaries insertion order in Python 3.7

以下是我的代码和结论。

初始化后,d2print(d2) 打印相同的值:

❯ python
Python 3.7.12 (default, Sep 10 2021, 17:29:55) 
[Clang 12.0.5 (clang-1205.0.22.9)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> d2 = {1: {1: 4, 2: 5, 3: 6}, 
      2: {7: 13, 8: 14, 9: 15, 10: 16, 11: 17, 12: 18},
      3: {1: 1, 2: 9, 3: 4}}
>>> d2
{1: {1: 4, 2: 5, 3: 6}, 2: {7: 13, 8: 14, 9: 15, 10: 16, 11: 17, 12: 18}, 3: {1: 1, 2: 9, 3: 4}}
>>> print(d2)
{1: {1: 4, 2: 5, 3: 6}, 2: {7: 13, 8: 14, 9: 15, 10: 16, 11: 17, 12: 18}, 3: {1: 1, 2: 9, 3: 4}}

排序后,d2print(d2) 打印出相同的值。

>>> import operator
>>> for keys in d2.keys():
...  sorted_tuples = sorted(d2[keys].items(), key=operator.itemgetter(1), reverse=True)
...  d2[keys] = {k: v for k, v in sorted_tuples}
... 
>>> print(d2)
{1: {3: 6, 2: 5, 1: 4}, 2: {12: 18, 11: 17, 10: 16, 9: 15, 8: 14, 7: 13}, 3: {2: 9, 3: 4, 1: 1}}
>>> d2
{1: {3: 6, 2: 5, 1: 4}, 2: {12: 18, 11: 17, 10: 16, 9: 15, 8: 14, 7: 13}, 3: {2: 9, 3: 4, 1: 1}}

但是,在使用漂亮的打印模块时,我能够复制您的行为。

>>> from pprint import pprint as pp
>>> pp(print(d2))
{1: {3: 6, 2: 5, 1: 4}, 2: {12: 18, 11: 17, 10: 16, 9: 15, 8: 14, 7: 13}, 3: {2: 9, 3: 4, 1: 1}}
>>> pp(d2)
{1: {1: 4, 2: 5, 3: 6},
 2: {7: 13, 8: 14, 9: 15, 10: 16, 11: 17, 12: 18},
 3: {1: 1, 2: 9, 3: 4}}

在漂亮的打印模块中禁用字典排序后,我就能获得您想要的输出。

>>> pprint.sorted = lambda x, key=None: x
>>> pp(d2)
{1: {3: 6, 2: 5, 1: 4},
 2: {12: 18, 11: 17, 10: 16, 9: 15, 8: 14, 7: 13},
 3: {2: 9, 3: 4, 1: 1}}
>>> pp(print(d2))
{1: {3: 6, 2: 5, 1: 4}, 2: {12: 18, 11: 17, 10: 16, 9: 15, 8: 14, 7: 13}, 3: {2: 9, 3: 4, 1: 1}}

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    相关资源
    最近更新 更多