1

Here's the list I'm trying to convert (arbitrary numbers):

[['2 4', '18', '4', '32', '2'], ['2 4', '13', '9', '12', '4'], ['3 7', '435', '2
3', '123', '4', '3', '234', '34']]

And here is the dictionary it returns (close, but not quite). Notice how the values are out of order. I need them to be in the same order as the list:

{0: {'2': 0, '18': 0, '32': 0, '2 4': 0, '4': 0}, 1: {'9': 0, '13': 0, '12': 0,
'2 4': 0, '4': 0}, 2: {'23': 0, '34': 0, '3': 0, '123': 0, '4': 0, '234': 0, '43
5': 0, '3 7': 0}}

And finally, here is the code I'm using to convert it:

iterator = 0 
myDict = {} 

for listItem in myList: 
    for item in listItem[1:]: 
        myDict[iterator] = dict.fromkeys(listItem, 0) 
iterator +=1 

edit: I forgot to mention that I'm trying to cut the first item in each list out of its corresponding dictionary.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
Drac
  • 47
  • 4

1 Answers1

5

In python, dicts are inherently unordered. This is for the reason that they are typically implemented via hash tables, which are more efficient than a simple associative array. Instead, you should use an OrderedDict, which acts just like a dict, but also remembers order:

from collections import OrderedDict

iterator = 0 
myDict = OrderedDict()

for listItem in myList:
    myDict[iterator] = OrderedDict.fromkeys(listItem[1:], 0)
    iterator += 1

Note: There's no reason to use an inner for loop here as well as fromkeys; you were just adding the entire listItem list in the first place since you weren't using item at all. If you wanted to use item you would have had to do this, without fromkeys, just using ordinary assignment:

from collections import OrderedDict

iterator = 0 
myDict = OrderedDict()

for listItem in myList:
    myDict[iterator] = OrderedDict()
    for item in listItem[1:]
        myDict[iterator][item] = 0
    iterator += 1

As a final note, python gives you nice tools so that you can write the whole thing as a one-liner using a generator expression and enumerate:

myDict = OrderedDict((i, OrderedDict.fromkeys(listItem[1:], 0))
                     for i, listItem in enumerate(myList))
Lily Chung
  • 2,919
  • 1
  • 25
  • 42
  • Yeah it's how you have it in my code, I just didn't notice that when I posted. Thanks! – Drac Jun 10 '14 at 05:10
  • @Drac I edited my answer since your whole inner `for` loop was a little misguided. See the updated answer for details. – Lily Chung Jun 10 '14 at 05:14