【问题标题】:Python dictionary random output of itemsPython字典随机输出项目
【发布时间】:2017-12-18 01:38:47
【问题描述】:

我正在从 firebase 检索数据作为字典列表。当我打印列表时,它的顺序不同。

例如:

print(list(mydictionary.keys())[0])

这个 0 元素总是不同的,print 给出不同的输出。我想在数据库中以相同的顺序打印,或者在我首先将数据作为列表时使其相同。有可能吗?

【问题讨论】:

  • Dict 无法向您保证订单。您如何准确地从 firebase 获取数据?从 firebase 获取数据时,尝试将键存储在列表中

标签: python database dictionary firebase firebase-realtime-database


【解决方案1】:

我认为您想要的是 OrderedDict 对象,它在添加键时保留键的顺序。在 python2.7+ 中,这是collections 模块的一部分:

>>> from collections import OrderedDict
>>> a = OrderedDict()
>>> a['blah'] = 4
>>> a['other'] = 5
>>> a['another'] = 6
>>> print(a)
OrderedDict([('blah', 4), ('other', 5), ('another', 6)])
>>> print(dict(a))
{'another': 6, 'blah': 4, 'other': 5}

我没有使用 firebase 的经验,所以这个答案在这个特定的用法中可能没有帮助。

【讨论】:

    【解决方案2】:

    如果你想保持秩序,请使用OrderedDict

    from collections import OrderedDict
    
    keys = list("1234")
    values = ["one", "two", "three", "four"]
    
    order_preserving_dict = OrderedDict(zip(keys, values))
    

    至于字典为什么不保留顺序,我可以解释,但你最好看看Why is the order in dictionaries and sets arbitrary?

    【讨论】:

      【解决方案3】:

      使用函数sorted()

      s = {0:1,h:t,1:1,10:2,2:1} for key,val in sorted(s.items()): print key, val

      或者在你的情况下

      print(sorted(list(mydictionary.keys())[0]))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-16
        • 1970-01-01
        • 1970-01-01
        • 2010-11-04
        • 2018-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多