简体   繁体   中英

Python dictionary with list as values: how do I select values?

I have a dictionary with lists as values:

d = {'a':[0,1],'b':[2,3]}

I want to create a dataframe with one column for the key and two columns for the values in the list:

|key |val1 |val2 |
|----|-----|-----|
|a   |0    |1    |
|b   |2    |3    |
|----|-----|-----|

My plan was to create three lists and just add these to a new dataframe. Works fine for the keys, but I don't know how to separate the elements in the list contained as values.

Here is what I tried:

key = d.keys()
val1 = d.values()[0]
val2 = d.values()[1]

What is the indexing of elements of a list that is stored as values in a dictionary?

So first of all if you want to create a data frame from a dictionary there is this method

import pandas as pd

pd.DataFrame.from_dict(d, orient='index')

Check the doc to understand what orient is doing. As per how to create this you can see the command yourself.

Also if you want to access the elements of the list and create the dataframe on your own you can do this

for val in d.values():
    print(val[0])
    print(val[1])
    #work with them

You can collect all these values in list as shown here by accessing the elements and then you can create dataframe pd.Dataframe()

if you want to "manually" to select the elemnts for your columns you can use:

{'key': list(d.keys()), **({'val%s' % i: list(map(lambda x: x[i], d.values())) for i in range(len(list(d.values())[0]))})}

output:

{'key': ['a', 'b'], 'val0': [0, 2], 'val1': [1, 3]}

to get the DataFrame:

pd.DataFrame({'key': list(d.keys()), **({'val%s' % i: list(map(lambda x: x[i], d.values())) for i in range(len(list(d.values())[0]))})})

output: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM