Blue482
Blue482

Reputation: 3156

How to construct a dict from lists or numpy arrays?

Can you please teach me to construct a dict from lists?

I have two lists:

A = [1, 2, 0, 0, 3]

and

B = ['HAM', 'SPAM', 'HAM', 'HAM', 'SPAM']

I want a dict like this:

Dict = [
...     {'Count': 1., 'Class': 'HAM'},
...     {'Count': 2., 'Class': 'SPAM'},
...     {'Count': 0., 'Class': 'HAM'},
...     {'Count': 0., 'Class': 'HAM'},
...     {'Count': 3., 'Class': 'SPAM'},
... ]

Which include two feature keys 'Count' and 'Class' as well...

Much appreciated! Thanks.

Upvotes: 2

Views: 90

Answers (4)

famousgarkin
famousgarkin

Reputation: 14126

The Dict = [{}, {}, ...] construct you have there is not a dict but a list ([]) of dicts ({}).

To get the required result using zip and list comprehension:

>>> A = [1, 2, 0, 0, 3]
>>> B = ['HAM', 'SPAM', 'HAM', 'HAM', 'SPAM']

>>> [{'Count': a, 'Class': b} for a, b in zip(A, B)]
[{'Count': 1, 'Class': 'HAM'},
 {'Count': 2, 'Class': 'SPAM'},
 {'Count': 0, 'Class': 'HAM'},
 {'Count': 0, 'Class': 'HAM'},
 {'Count': 3, 'Class': 'SPAM'}]

Upvotes: 1

redcrow
redcrow

Reputation: 1823

That's not a dict, but a list (of dictionaries). Anyway, if what you want is this:

data = [
            {'Count': 1., 'Class': 'HAM'},
            {'Count': 2., 'Class': 'SPAM'},
            {'Count': 0., 'Class': 'HAM'},
            {'Count': 0., 'Class': 'HAM'},
            {'Count': 3., 'Class': 'SPAM'}
       ]

then:

data = [{'Count': float(x[0]), 'Class': x[1]} for x in zip(A, B)]

update

I've updated my answer because I've just noticed that you required a float as value for 'Count'.

Upvotes: 2

shx2
shx2

Reputation: 64318

Instead of a list of dicts (i.e. records), you can use pandas.

pandas is perfect for representing this kind of data.

df = pd.DataFrame({ 'Count': A, 'Class': B})
df
=> 
  Class  Count
0   HAM      1
1  SPAM      2
2   HAM      0
3   HAM      0
4  SPAM      3

[5 rows x 2 columns]

df.Class
=>
0     HAM
1    SPAM
2     HAM
3     HAM
4    SPAM
Name: Class, dtype: object

df.Class[1]
=> 'SPAM'

df.ix[1]
=>
Class    SPAM
Count       2
Name: 1, dtype: object

df.ix[1].Class
=> 'SPAM'

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117886

>>> A = [1, 2, 0, 0, 3]
>>> B = ['HAM', 'SPAM', 'HAM', 'HAM', 'SPAM']

>>> zip(A,B)
[(1, 'HAM'), (2, 'SPAM'), (0, 'HAM'), (0, 'HAM'), (3, 'SPAM')]

>>> [{'Count':i[0], 'Class':i[1]} for i in zip(A,B)]

Output

[{'Count': 1, 'Class': 'HAM'},
 {'Count': 2, 'Class': 'SPAM'},
 {'Count': 0, 'Class': 'HAM'},
 {'Count': 0, 'Class': 'HAM'},
 {'Count': 3, 'Class': 'SPAM'}]

Upvotes: 1

Related Questions