David__
David__

Reputation: 375

How to go from a values_list to a dictionary of lists

I have a django queryset that returns a list of values:

[(client pk, timestamp, value, task pk), (client pk, timestamp, value, task pk),....,].

I am trying to get it to return a dictionary of this format:

{client pk:[[timestamp, value],[timestamp, value],...,], client pk:[list of lists],...,}

The values_list may have multiple records for each client pk. I have been able to get dictionaries of lists for client or task pk using:

def dict_from_vl(vls_list):
    keys=[values_list[x][3] for x in range(0,len(values_list),1)]
    values = [[values_list[x][1], values_list[x][2]] for x in range(0,len(values_list),1)]
    target_dict=dict(zip(keys,values))
    return target_dict

However using this method, values for the same key write over previous values as it iterates through the values_list, rather than append them to a list. So this works great for getting the most recent if the values list is sorted oldest records to newest, but not for the purpose of creating a list of lists for the dict value.

Upvotes: 1

Views: 1620

Answers (4)

Will Cheng
Will Cheng

Reputation: 199

For better speed, I suggest you don't create the keys and values lists separately but simply use only one loop:

tgt_dict = defaultdict(list)
for row in vas_list:
    tgt_dict[row[0]].append([row[1], row[2]])

Upvotes: 1

DMac the Destroyer
DMac the Destroyer

Reputation: 5290

I know in Python you're supposed to cram everything into a single line, but you could do it the old fashioned way...

def dict_from_vl(vls_list):
    target_dict = {}
    for v in vls_list:
        if v[0] not in target_dict:
            target_dict[v[0]] = []
        target_dict[v[0]].append([v[1], v[2]])
    return target_dict

Upvotes: 1

Łukasz Milewski
Łukasz Milewski

Reputation: 1911

from collections import defaultdict
d = defaultdict(list)
for x in vls_list:
   d[x].append(list(x[1:]))

Although I'm not sure if I got the question right.

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363757

Instead of target_dict=dict(zip(keys,values)), do

target_dict = defaultdict(list)
for i, key in enumerate(keys):
    target_dict[k].append(values[i])

(defaultdict is available in the standard module collections.)

Upvotes: 1

Related Questions