Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert key-value pair into dictionary at a specified position?

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' for 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.

like image 874
DeepApp Avatar asked Jun 06 '17 13:06

DeepApp


People also ask

Can we add key-value pair to a dictionary using the append () function?

We can make use of the built-in function append() to add elements to the keys in the dictionary.

How do I add an item to a dictionary key in Python?

If you want to add a new key to the dictionary, then you can use the assignment operator with the dictionary key. This is pretty much the same as assigning a new value to the dictionary. Since Python dictionaries are mutable, when you use the assignment operator, you're simply adding new keys to the datastructure.


1 Answers

This is a follow-up on nurp's answer. Has worked for me, but offered with no warranty.

# Insert dictionary item into a dictionary at specified position: 
def insert_item(dic, item={}, pos=None):
    """
    Insert a key, value pair into an ordered dictionary.
    Insert before the specified position.
    """
    from collections import OrderedDict
    d = OrderedDict()
    # abort early if not a dictionary:
    if not item or not isinstance(item, dict):
        print('Aborting. Argument item must be a dictionary.')
        return dic
    # insert anywhere if argument pos not given: 
    if not pos:
        dic.update(item)
        return dic
    for item_k, item_v in item.items():
        for k, v in dic.items():
            # insert key at stated position:
            if k == pos:
                d[item_k] = item_v
            d[k] = v
    return d

d = {'A':'letter A', 'C': 'letter C'}
insert_item(['A', 'C'], item={'B'})
## Aborting. Argument item must be a dictionary.

insert_item(d, item={'B': 'letter B'})
## {'A': 'letter A', 'C': 'letter C', 'B': 'letter B'}

insert_item(d, pos='C', item={'B': 'letter B'})
# OrderedDict([('A', 'letter A'), ('B', 'letter B'), ('C', 'letter C')])
like image 160
PatrickT Avatar answered Sep 21 '22 20:09

PatrickT