Alex
Alex

Reputation: 2412

Python seems to randomly invert list items during long loop

I have an array of dictionaries of the form:

[
    {
        generic_key: specific_key,
        generic_value: specific_value
    }
    ...
]

I am trying to interpret this into an array of dictionaries of this form:

[
    {
        specific_key: specific_value
    }
    ...
]

I tried this:

new_array = []
for row in old_array:
    values = list(row.values())
    key = values[0]
    val = values[1]
    new_array.append({key: val})

This works in most cases, but in some, it swaps them around to form a dict like this:

{
    specific_value: specific_key
}

I've looked at the source file, and the rows in which it does this are identical to the rows in which it does not do this.

It's perhaps worth mentioning that the list in question is about 3000 elements in length.

Am I doing something stupid? I guess that maybe list(row.values()) does not necessarily preserve the order, but I don't see why it wouldn't.

EDIT fixed code typo suggesting that it was appending sets

Upvotes: 0

Views: 55

Answers (1)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

The order in which dict keys/values are enumerated is ostensibly arbitrary (there's certainly a logic to it, and as of I think python3.7+, it's consistent, but while I don't know off the top of my head what the ordering criteria are) - if you wanted order, you would have used a list instead of a dict to store them in the first place. If generic_key and generic_value are the same each time, then the ideal way to handle this problem is to simply extract by key:

key = row['generic_key']
value = row['generic_value']

If this isn't the case but there is a consistent way to differentiate between generic_key and generic_value, then you can grab both the keys and values, and do that:

items = tuple(row.items())
if items[0][0] is the generic_key:  # insert whatever condition you need to here
    key = items[0][1]
    value = items[1][1]
else
    key = items[1][1]
    value = items[0][1]

Upvotes: 3

Related Questions