milandjukic88
milandjukic88

Reputation: 1115

Dictionary values are not ordered python

When i get data from database like this:

filteredData = NaseljenoMesto.objects.filter(naseljenomesto_drzava=1).values('id','sifraMesta','nazivMesta','naseljenomesto_drzava__naziv')

Why output values are not in order like above:

Output is: naseljenomesto_drzava__naziv,sifraMesta,nazivMesta,id

Upvotes: 0

Views: 240

Answers (4)

John Percival Hackworth
John Percival Hackworth

Reputation: 11531

A basic dictionary does not maintain insertion order. A dictionary is "ordered" by the hash values of the keys rather than the lexical values of the keys.

Upvotes: 3

Apostolos Apostolidis
Apostolos Apostolidis

Reputation: 189

at some point of your progress in programming, you will realize that if order matters for you, then you probably have to reconsider using a dictionary in the first place

Upvotes: 1

mrKelley
mrKelley

Reputation: 3524

Python does not maintain order. If you want to have an ordered dictionary, check out the collections module from the standard library:

import collections
d = collections.OrderedDict()

It will behave like the python dictionaries you are used to, but maintain order.

Upvotes: 2

bgporter
bgporter

Reputation: 36504

If you need a dict that maintains insertion order, Python versions >= 2.7 include the OrderedDict class in the collections module.

A regular dict:

>>> ud = {}
>>> ud['first'] = 1
>>> ud['second'] = 2
>>> ud['third'] = 3
>>> ud.values()
[2, 3, 1]

An ordered dict:

>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od['first'] = 1
>>> od['second'] = 2
>>> od['third'] = 3
>>> od.values()
[1, 2, 3]

Upvotes: 2

Related Questions