cad
cad

Reputation: 13

list with xyz values to dictionary

I have a list:

list = [ '1', '1,'1', '-1','1','-1' ]

and need to convert it to a dictionary of dictionaries. The first three values in are x y z and the second set three values are x y z. The result should be:

d = { 0:{x:1,y:1,z:1}, 1:{x:-1,y:1,z:-1}}

My attempt:

mylist=[1,1,1,-1,1,-1]
count = 1
keycount = 0
l = {'x':' ','y':' ', 'z':' '}
t = {}
for one in mylist:
        if count == 1:
                l['x'] = one
                print l
        if count == 2:
                l['y'] = one
                print l
        if count == 3:
                l['z'] = one
                print l
                count = 0
                t[keycount] = l
                l = {}
                keycount += 1
        count = count + 1
print t

But in the result it switches some of the keys of the dictionary? Does anyone have a better solution?

Upvotes: 1

Views: 2193

Answers (4)

pillmuncher
pillmuncher

Reputation: 10162

For Python 3:

>>> from itertools import cycle
>>>
>>> alist = ['1', '1', '1', '-1', '1', '-1']
>>>
>>> dict(enumerate(map(dict, zip(*[zip(cycle('xyz'), map(int, alist))] * 3))))
{0: {'y': 1, 'x': 1, 'z': 1}, 1: {'y': 1, 'x': -1, 'z': -1}}

I know it's horrible, but still...

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816374

Dictionary items are unordered.

However, Python 2.7 introduced OrderedDict which retains the order in which the items have been added.

You can do:

>>> from collections import OrderedDict
>>> d = {}
>>> k = ('x', 'y', 'z')
>>> for i,j in enumerate(range(0, len(mylist), 3)):
...     d[i] = OrderedDict(zip(k, l[j:j+3]))
...
>>> d
{0: OrderedDict([('x', '1'), ('y', '1'), ('z', '1')]), 1: OrderedDict([('x', '-1'), ('y', '1'), ('z', '-1')])}

But normally there is no reason to have the items ordered. You access the value via d[0]['x'] anyway and there it does not matter in which order the items are.

But, if you want to have the items in d in order, I suggest you use a list instead of a dictionary. Your keys are only numerical anyway, there is not need for a dictionary.

Upvotes: 1

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

A bit complicated one:

l = [ '1', '1', '1', '-1', '1', '-1' ]

dicts = [dict(zip(['x', 'y', 'z'], l[i:i+3])) for i in range(0, len(l), 3)]
result = dict(enumerate(dicts))

print result #prints {0: {'y': '1', 'x': '1', 'z': '1'}, 1: {'y': '1', 'x': '-1', 'z': '-1'}}

Upvotes: 3

Petar Ivanov
Petar Ivanov

Reputation: 93030

d = {}
for i in range(len(myList)/3):
    d[i] = {'x':myList[3*i], 'y':myList[3*i+1], 'z':myList[3*i+2]}

Upvotes: 0

Related Questions