0

Is it possible to append key-value pairs to a dictionary?

For example, I want a dictionary like this: a = {4:"Hello", 1:"World"} can that be done using dictionaries? If it can't, is there an alternate data structure that can do that?

I want it ordered in order I add them. In this case, I added the key-value pair 4:"Hello" first.

3 Answers3

2
from collections import OrderedDict
order_dict = OrderedDict()
order_dict[4] = "Hello"
order_dict[3] = "World"
order_dict[5] = "Bah"
print order_dict

Outputs:

OrderedDict([(4, 'Hello'), (3, 'World'), (5, 'Bah')])

Print key and values:

for key, value in order_dict.iteritems() :
    print key, value

Outputs:

4 Hello
3 World
5 Bah
Avión
  • 7,963
  • 11
  • 64
  • 105
1

Yes it can.

From the module collections, use OrderedDict to get the sequence of adding keys retained.

0

use collections.OrderedDict to have ordered dictionaries:

>>> from collections import OrderedDict
>>> original = OrderedDict({1:"world"})
>>> new = OrderedDict({4:"hello"})
>>> new.update(original)
>>> new
# OrderedDict([(4, 'hello'), (1, 'World')])

This would work only for additions at front. For insertions at random locations, see Borja's answer

Community
  • 1
  • 1
Ayush
  • 3,695
  • 1
  • 32
  • 42