Carlos
Carlos

Reputation: 3

Appending to a dictionary of lists elements from a nested list in order

I've created a dictionary with keys that represent relative distances and values that are empty lists. I would like to populate these values--empty lists--with entries from a nested list that are the values of the relative distances. My problem is that when I populate the values of the dictionary, its entries are not being filled in the order in which they appear in the nested list.

This is the closest I've gotten to solving the problem:

relDistDic = { 'a':[], 'b': [] } # dictionary with relative distances

relDist = [[1,2,3], [4,5,6], [7,8,9], [10,11,12] ] #nested list with dstncs

for v in relDistDic.values():
    for element in relDist:
        if len(v) < 2 :
            v.append(element)

I would like to get the following output:

{ 'a':[[1,2,3], [4,5,6]], 'b': [[7,8,9], [10,11,12]] }

But instead I am getting this:

{ 'a':[[1,2,3], [4,5,6]], 'b': [[1,2,3], [4,5,6]] }

Any help or comments are greatly appreciated, thanks!

Upvotes: 0

Views: 135

Answers (2)

Michael Bianconi
Michael Bianconi

Reputation: 5232

Dictionaries are unordered! The order that you insert elements with not be the same order that they appear as when you iterate through them.

Not only that, but in

for v in relDistDic.values():
  for element in relDist:
    if len(v) < 2:
      v.append(element)

For each value in relDist, you're only appending the first two (because of if len(v) < 2). Perhaps you meant to remove the items from relDist as you append them?

To do so, use pop().

for v in relDistDic.values():
  for i in range(2):
    if len(relDist) > 0:
      v.append(relDist.pop(0))

Upvotes: 1

vekerdyb
vekerdyb

Reputation: 1263

What about:

relDist = [[1,2,3], [4,5,6], [7,8,9], [10,11,12] ] #nested list with dstncs

relDistDic = { 'a': relDist[:2], 'b': relDist[2:] } # dictionary with relative distances

Upvotes: 0

Related Questions