天天看點

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

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

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

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')])

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