将键值对插入字典中的指定位置 [英] Insert key-value pair into dictionary at a specified position

查看:2017
本文介绍了将键值对插入字典中的指定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从YAML文档加载的python字典中的指定位置插入键值对?

How would I insert a key-value pair at a specified location in a python dictionary that was loaded from a YAML document?

例如,如果字典是:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

我希望插入元素'Phone':'1234'

之前年龄和之后名称.这只是一个例子.我将要使用的实际字典很大(已解析的YAML文件),因此删除和重新插入可能会比较麻烦(我不太了解).

before Age, and after Name. This is just an example. The actual dictionary I shall be working on is quite large (parsed YAML file), so deleting and reinserting might be a bit cumbersome(I don't really know).

如果我可以在OrderedDict中插入指定位置,那也可以.

If I am given a way of inserting into a specified position in an OrderedDict, that would be okay too.

推荐答案

在python上<在3.7(或cpython< 3.6)中,您无法控制标准字典中对的排序.

On python < 3.7 (or cpython < 3.6), you cannot control the ordering of pairs in a standard dictionary.

如果您打算经常执行任意插入,我的建议是使用列表存储键,并使用字典存储值.

If you plan on performing arbitrary insertions often, my suggestion would be to use a list to store keys, and a dict to store values.

mykeys = ['Name', 'Age', 'Class']
mydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} # order doesn't matter

k, v = 'Phone', '123-456-7890'

mykeys.insert(mykeys.index('Name')+1, k)
mydict[k] = v

for k in mykeys:
    print(f'{k} => {mydict[k]}')

# Name => Zara
# Phone => 123-456-7890
# Age => 7
# Class => First


如果您打算用其内容不太可能改变的顺序来初始化字典,则可以使用collections.OrderedDict结构来维护插入顺序.


If you plan on initialising a dictionary with ordering whose contents are not likely to change, you can use the collections.OrderedDict structure which maintains insertion order.

from collections import OrderedDict

data = [('Name', 'Zara'), ('Phone', '1234'), ('Age', 7), ('Class', 'First')] 
odict = OrderedDict(data)
odict
# OrderedDict([('Name', 'Zara'),
#              ('Phone', '1234'),
#              ('Age', 7),
#              ('Class', 'First')])

请注意,OrderedDict不支持在任意位置插入(它只记住将键插入字典的顺序).

Note that OrderedDict does not support insertion at arbitrary positions (it only remembers the order in which keys are inserted into the dictionary).

这篇关于将键值对插入字典中的指定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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