python添加键值对_将键值对插入字典中的指定位置

在Python中,如果要将键值对插入到从YAML文件加载的字典的指定位置,可以使用列表来保存键,使用字典来存储值。对于大型字典,这种方法比删除和重新插入更有效。另一种方式是使用collections.OrderedDict,它会保持插入顺序,但不支持任意位置的插入。
摘要由CSDN通过智能技术生成

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

For example if a dictionary is:

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

I wish to insert the element 'Phone':'1234'

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).

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

解决方案

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值