Reza
Reza

Reputation: 113

the output is not in correct order

i have a code in python2.7 which gets a line of text as its list elements and returns it as json. here is the code:

import itertools

lines=["Hamlet"
   ,"William Shakespeare",
   "Edited Barbara B Mowat Paul Werstine"
   ,"Michael Poston Rebecca Niles"]
LinesMap=dict()
for line in lines:
    list=[l for l in line.split(' ')]
    d = dict(itertools.izip_longest(*[iter(list)] * 2, fillvalue=None))
    LinesMap.update(d)

print(LinesMap)

the output is:

{'William': 'Shakespeare', 'Edited': 'Barbara', 'B': 'Mowat',    

'Michael':'Poston', 'Paul': 'Werstine', 'Rebecca': 'Niles', 'Hamlet': None}

whereas it should be:

{'Hamlet': None, 'William': 'Shakespeare', 'Edited': 'Barbara', 

'B':'Mowat', 'Paul': 'Werstine', 'Michael': 'Poston', 'Rebecca': 'Niles'}

if i make the list longer it will be even worse! why this is not in correct order? but when i run the same code in python3.6,with python3 syntax of course, the order is correct. the python3.6 code is:

import itertools

lines=["Hamlet"
   ,"William Shakespeare",
   "Edited Barbara B Mowat Paul Werstine"
   ,"Michael Poston Rebecca Niles"]
LinesMap=dict()
for line in lines:
   list=[l for l in line.split(' ')]
   d = dict(itertools.zip_longest(*[iter(list)] * 2, fillvalue=None))
   LinesMap = {**LinesMap, **d}

print(LinesMap) 

this is one problem. the other one is that for short lists it's ok and runs properly. but when the list is longer and has too many elements, the output does not show anything and it seems to be broken. this is in windows and in linux it doesn't break. what is the problem?

ps: i have to run it in python 2.7 for some reasons!

Upvotes: 0

Views: 144

Answers (1)

Ben Quigley
Ben Quigley

Reputation: 727

The Python dict object has no intrinsic order except in quite recent versions of Python, so you can't assume you'll get objects out in the same order you put them in.

If you need that functionality, there is an OrderedDict object you can use.

import random
from collections import OrderedDict

# Normal dict behavior:
numbers = {}
random_nums = (random.random() for _ in range(1000))
for i in random_nums:
    numbers[i] = random.random()
assert list(numbers.keys()) != list(random_nums)

# Ordered dict behavior:
numbers = OrderedDict()
for i in random_nums:
    numbers[i] = random.random()
assert list(numbers.keys()) == list(random_nums)

Upvotes: 4

Related Questions