data dictionary items to list code example

Example 1: dictionary in python does not support append operation

dict_append = {"1" : "Python", "2" : "Java"}
dict_append.update({"3":"C++"})  # append doesn't supported in dict 
								 # instead , use update in dict
print(dict_append)
# output : {'1': 'Python', '2': 'Java', '3': 'C++'}

Example 2: python 3.7 insert at place in dict

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