How do you insert an item into a dictionary (in python 3.7.2)?

Chris Angelico rosuav at gmail.com
Fri Jun 28 11:53:30 EDT 2019


On Sat, Jun 29, 2019 at 1:51 AM Jon Ribbens via Python-list
<python-list at python.org> wrote:
>
> On 2019-06-28, Larry Martell <larry.martell at gmail.com> wrote:
> > On Fri, Jun 28, 2019 at 11:10 AM CrazyVideoGamez
> ><jasonanyilian at gmail.com> wrote:
> >>
> >> How do you insert an item into a dictionary? For example, I make a dictionary called "dictionary".
> >>
> >> dictionary = {1: 'value1', 2: 'value3'}
> >>
> >> What if I wanted to add a value2 in the middle of value1 and value3?
> >
> > Dicts are not ordered. If you need that use an OrderedDict
> > (https://docs.python.org/3.7/library/collections.html#collections.OrderedDict)
>
> This is no longer true from Python 3.6 onwards - dicts are ordered.
> There's no way to insert an item anywhere other than at the end though.

They retain order, but they're not an "ordered collection" the way a
list is. You can't logically insert into a sequence, because it's not
a sequence. You can't say "what's the 43rd entry in this dict?"
because it doesn't have a 43rd entry. All it has is a recollection of
the order things were inserted.

ChrisA



More information about the Python-list mailing list