Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从python中现有的dict列表中获取子集dict列表_Python_Python 3.x_Pandas_Dataframe - Fatal编程技术网

从python中现有的dict列表中获取子集dict列表

从python中现有的dict列表中获取子集dict列表,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,下面是一个dict列表,每个dict包含两个键 original_list = [ { 'label': 'First Name', 'value': 'Leo', }, { 'label': 'Last Name', 'value': 'Lee', }, { 'label': 'Gender', 'value': 'Male', }, {

下面是一个dict列表,每个dict包含两个键

original_list = [
    {
        'label': 'First Name',
        'value': 'Leo',
    },
    {
        'label': 'Last Name',
        'value': 'Lee',
    },
    {
        'label': 'Gender',
        'value': 'Male',
    },
    {
        'label': 'Age',
        'value': 35,
    },
    {
        'label': 'Telephone',
        'value': '13788995566',
    }
]                   
我想得到一个新的dict列表,其中只有一个键(“标签”)

# expecting output like below
new_list =  [
    {
        'label': 'First Name'
    },
    {
        'label': 'Last Name'
    },
    {
        'label': 'Gender'
    },
    {
        'label': 'Age'
    },
    {
        'label': 'Telephone'
    }
]
我知道一种四处走动的方法

new_list = [{'label': d['label']} for d in original_list]
print(new_list)
有没有更方便的方法


如果原始列表数据在一个数据帧中,如何获得相同的结果?

如果输入是
DataFrame
选择要按子集输出的列
[[]]
,并使用参数调用
orient='records'

df = pd.DataFrame(original_list)
print (df)
        label        value
0  First Name          Leo
1   Last Name          Lee
2      Gender         Male
3         Age           35
4   Telephone  13788995566

print (df[['label']].to_dict(orient='records'))
[{'label': 'First Name'}, 
 {'label': 'Last Name'}, 
 {'label': 'Gender'}, 
 {'label': 'Age'}, 
 {'label': 'Telephone'}]

就像你的一样!列表理解,甚至有点长:)但肯定还有一种方法:)


谢谢我只知道“orient”选项。如果标签不是唯一的,我们可以对df['label']中的标签执行[{'label':label}。unique()
[{e: i} for d in original_list for e,i in d.items() if e =='label']