是否可以添加< key,value>在python的字典结尾配对 [英] Is it possible to add <key, value> pair at the end of the dictionary in python

查看:141
本文介绍了是否可以添加< key,value>在python的字典结尾配对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我引入新的对,它被插入字典的开头。

When I introduce new pair it is inserted at the beginning of dictionary. Is it possible to append it at the end?

推荐答案

词典没有顺序,因此没有开始或结束。显示顺序是任意的。
如果您需要订单,您可以使用 c c c c 而不是 dict

Dictionaries have no order, and thus have no beginning or end. The display order is arbitrary. If you need order, you can use a list of tuples instead of a dict:

In [1]: mylist = []

In [2]: mylist.append(('key', 'value'))

In [3]: mylist.insert(0, ('foo', 'bar'))

您将能够轻松地将其转换为 dict 以后:

You'll be able to easily convert it into a dict later:

In [4]: dict(mylist)
Out[4]: {'foo': 'bar', 'key': 'value'}

或者,使用 collections.OrderedDict

Alternatively, use a collections.OrderedDict as suggested by IamAlexAlright.

这篇关于是否可以添加< key,value>在python的字典结尾配对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆