Mahesh
Mahesh

Reputation: 1333

Add new key-value pair at the beginning of a dictionary

I have list of dictionaries. Now, in every dictionary, i want to add a key value pair(key : 'message1') at the beginning of the dict, but when i add it , its getting added to the end.

Following is my code

data=[{
'message2': 'asd',
'message3': 'fgw',
'message4': 'fgeq',
'message5': 'gqe',
'message6': 'afgq',
'message7': 'major',
'message8': 'color-regular'
}]
for i in data:
    i['message1'] = '111'

Following is the output i am getting where message1 is appended in the end

[{'message2': 'asd',
'message3': 'fgw',
  'message4': 'fgeq',
  'message5': 'gqe',
  'message6': 'afgq',
  'message7': 'major',
  'message8': 'color-regular',
  'message1': '111'# i want this in the beginning}]

Please suggest a workaround

Upvotes: 3

Views: 6709

Answers (4)

Marcus Elwin
Marcus Elwin

Reputation: 1

Think this is also an alternative by using unpacking the original dict elements into a new dict with the new key-value pair:

def add_to_start(data: Dict, new_key: str, new_val: any) -> Dict:
    return {new_key: new_val, **data}

data = {
   'b': 22,
   'a': 5,
   'c': 7,
   'd': 8
}

print(add_to_start(data, 'f', 11))
# {'f': 11, 'b': 22, 'a': 5, 'c': 7, 'd': 8}

Upvotes: -1

kwick
kwick

Reputation: 787

You can do it like this:

dict1 = {
    '1': 'a',
    '2': 'b'
}

items = list(dict1.items())
items.insert(0, ('0', 'z'))
dict1 = dict(items)

print(dict1)
# {'0': 'z', '1': 'a', '2': 'b'}

Upvotes: 2

luipenox
luipenox

Reputation: 118

Simple way do to this can be create a dict first:

data = {'m1': 'A', 'm2': 'D'}

and then use update:

data.update({'m3': 'C', 'm4': 'B'})

Result will be {'m1': 'A', 'm2': 'D', 'm3': 'C', 'm4': 'B'}. The assumption is python version 3.7+ for an ordered dict. In the other way, you can use collections.OrderedDict.

Upvotes: 3

cs95
cs95

Reputation: 402253

On python3.7+ (cpython3.6+), dictionaries are ordered, so you can create a new dict with "message" as the first key:

for i, d in enumerate(data):
    data[i] = {'message': '111', **d}

data      
[{'message': '111',
  'message2': 'asd',
  'message3': 'fgw',
  'message4': 'fgeq',
  'message5': 'gqe',
  'message6': 'afgq',
  'message7': 'major',
  'message8': 'color-regular'}]

Upvotes: 3

Related Questions