【问题标题】:Insert key in default dict to the front [duplicate]将默认字典中的键插入到前面[重复]
【发布时间】:2016-05-12 11:17:27
【问题描述】:

我有这个 defaultdict 和一个字符串变量:

my_dict = defaultdict(<class 'str'>, {2: 'bear', 3: 'fish', 4: 'dog', 5: 'goat'})

str_match = "goat"

我想弹出my_dict中与str_match具有相同值的键,并将其插入到前面。像这样的:

my_dict = defaultdict(<class 'str'>, {5: 'goat', 2: 'bear', 3: 'fish', 4: 'dog'})

到目前为止我有:

for key, value in list(my_dict.items()):
    if value == str_match:
        my_dict.pop(key)

有没有办法可以做到这一点?

【问题讨论】:

  • 你是什么意思在前面?字典没有排序。
  • 不带字典 - '在前面' 没有意义,因为字典没有排序。下次访问字典时,“在前面”对可能不在同一个位置。
  • Python 3.2 引入了move_to_end 方法,可让您将键移动到键序列的开头或结尾。 (键按其插入顺序进行排序;它们不能任意排序。)

标签: python


【解决方案1】:

您可以在 python 2.7 或更高版本中使用 OrderedDict。文档链接为:https://docs.python.org/2/library/collections.html#collections.OrderedDict

【讨论】:

    猜你喜欢
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 2021-07-27
    • 2011-06-29
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多