Euxitheos
Euxitheos

Reputation: 325

Assign a Dictionary Key to a Given List Using Python

Can I assign a dictionary key to a list OR list of lists. Then take averages, cov, etc it:

input={'03439', '03440'}
list of list= [[PersonA, 7, 8, 9, 10, 11],[PersonB, 12, 13, 14, 15, 16]]

Desired Output

{'03439': [PersonA, 7, 8, 9, 10, 11],'03440':[PersonB, 12, 13, 14, 15, 16]}

If I wanted to take the average values of the above, can I do so even with part of this being string and the other values?

Upvotes: 1

Views: 93

Answers (3)

timgeb
timgeb

Reputation: 78700

Use zip and just construct a dict:

>>> dict(zip(input, list_of_lists))
{'03439': ['PersonA', 7, 8, 9, 10, 10], '03440': ['PersonB', 12, 13, 14, 15, 16]}

Upvotes: 0

Pynchia
Pynchia

Reputation: 11590

In case you wanted to calculate the average there and then you could do

>>> PersonA = 'Pino'
>>> PersonB = 'Gino'
>>> i=('03439', '03440') # tuple
>>> l=[[PersonA, 7, 8, 9, 10, 11],[PersonB, 12, 13, 14, 15, 16]]
>>> av={k:[v[0], sum(v[1:])/(len(v)-1)] for k,v in zip(i,l)}
>>> av
{'03439': ['Pino', 9.0], '03440': ['Gino', 14.0], }

Nota Bene: for the zipping to work input must be an iterable which can keep the order of its elements, e.g. a tuple or a list. Sets and plain dictionaries cannot do it.

And the answer is no, integers cannot be summed with strings

Upvotes: 2

repzero
repzero

Reputation: 8412

Using izip and list comprehension

from itertools import izip
     [dict([(x,y)])for x,y in izip({'03439', '03440'},[['PersonA', 7, 8, 9, 10, 11],['PersonB', 12, 13, 14, 15, 16]])]

output

[{'03439': ['PersonA', 7, 8, 9, 10, 11]}, {'03440': ['PersonB', 12, 13, 14, 15, 16]}]

Upvotes: 0

Related Questions