拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 从选择特定值的字典串列创建字典

从选择特定值的字典串列创建字典

白鹭 - 2022-02-12 1946 0 0

我有一个字典串列如下,我想创建一个字典来存盘串列中的特定资料。

test_list = [
    {
        'id':1,
        'colour':'Red',
        'name':'Apple',
        'edible': True,
        'price':100
    },
    {
        'id':2,
        'colour':'Blue',
        'name':'Blueberry',
        'edible': True,
        'price':200
    },
    {
        'id':3,
        'colour':'Yellow',
        'name':'Crayon',
        'edible': False,
        'price':300
    }
]

例如,一个新字典只存盘各种项目的 {id, name, price}。

我创建了几个串列:

id_list = []
name_list = []
price_list = []

然后我将我想要的资料添加到每个串列中:

for n in test_list:
   id_list.append(n['id']
   name_list.append(n['name']
   price_list.append(n['price']

但我不知道如何创建字典(或更合适的结构?)以我想要的 {id, name, price} 格式存盘资料。感谢帮助!

uj5u.com热心网友回复:

如果你没有太多资料,你可以使用这个嵌套串列/字典理解:

keys = ['id', 'name', 'price']
result = {k: [x[k] for x in test_list] for k in keys}

这会给你:


{
  'id': [1, 2, 3],
  'name': ['Apple', 'Blueberry', 'Crayon'],
  'price': [100, 200, 300]
}

uj5u.com热心网友回复:

我认为字典串列仍然是正确的资料格式,所以:

test_list = [
    {
        'id':1,
        'colour':'Red',
        'name':'Apple',
        'edible': True,
        'price':100
    },
    {
        'id':2,
        'colour':'Blue',
        'name':'Blueberry',
        'edible': True,
        'price':200
    },
    {
        'id':3,
        'colour':'Yellow',
        'name':'Crayon',
        'edible': False,
        'price':300
    }
]

keys = ['id', 'name', 'price']
limited = [{k: v for k, v in d.items() if k in keys} for d in test_list]

print(limited)

结果:

[{'id': 1, 'name': 'Apple', 'price': 100}, {'id': 2, 'name': 'Blueberry', 'price': 200}, {'id': 3, 'name': 'Crayon', 'price': 300}]

这很好,因为您可以访问它的部分,例如limited[1]['price'].

但是,pandas如果您不介意使用第三方库,您的用例非常适合

import pandas as pd

test_list = [
    {
        'id':1,
        'colour':'Red',
        'name':'Apple',
        'edible': True,
        'price':100
    },
    {
        'id':2,
        'colour':'Blue',
        'name':'Blueberry',
        'edible': True,
        'price':200
    },
    {
        'id':3,
        'colour':'Yellow',
        'name':'Crayon',
        'edible': False,
        'price':300
    }
]

df = pd.DataFrame(test_list)

print(df['price'][1])
print(df)

DataFrame 非常适合这些东西,并且只选择您需要的列:

keys = ['id', 'name', 'price']
df_limited = df[keys]
print(df_limited)

我更喜欢串列字典的原因是,操作串列字典会变得复杂且容易出错,并且访问单个记录意味着访问三个单独的串列 - 除了某些操作之外,这种方法没有很多优点如果您更频繁地访问单个属性,on list 会更快。但在这种情况下,pandas轻而易举地获胜。

在你问的评论中“假设我有item_names = ['Apple', 'Teddy', 'Crayon']并且我想检查这些项目名称中的一个是否在df_limited变量中,或者我猜df_limited['name']- 有没有办法做到这一点,如果是那么打印说价格,或操纵价格?”

There's many ways of course, I recommend looking into some online pandas tutorials, because it's a very popular library and there's excellent documentation and teaching materials online.

However, just to show how easy it would be in both cases, retrieving the matching objects or just the prices for them:

item_names = ['Apple', 'Teddy', 'Crayon']

items = [d for d in test_list if d['name'] in item_names]
print(items)
item_prices = [d['price'] for d in test_list if d['name'] in item_names]
print(item_prices)

items = df[df['name'].isin(item_names)]
print(items)
item_prices = df[df['name'].isin(item_names)]['price']
print(item_prices)

Results:

[{'id': 1, 'colour': 'Red', 'name': 'Apple', 'edible': True, 'price': 100}, {'id': 3, 'colour': 'Yellow', 'name': 'Crayon', 'edible': False, 'price': 300}]
[100, 300]

   id    name  price
0   1   Apple    100
2   3  Crayon    300
0    100
2    300

In the example with the dataframe there's a few things to note. They are using .isin() since using in won't work in the fancy way dataframes allow you to select data df[<some condition on df using df>], but there's fast and easy to use alternatives for all standard operations in pandas. More importantly, you can just do the work on the original df - it already has everything you need in there.

And let's say you wanted to double the prices for these products:

df.loc[df['name'].isin(item_names), 'price'] *= 2

.loc用于技术原因(您不能只修改资料框的任何视图),但在此答案中涉及的内容太多了 - 您将学习查看pandas. 不过,它非常干凈和简单,我相信你同意。(您也可以.loc用于前面的示例)

在这个简单的示例中,两者都立即运行,但您会发现pandas对于非常大的资料集执行得更好。此外,尝试使用您要求的方法(如接受的答案中提供的)撰写相同的示例,您会发现它并不那么优雅,除非您再次将所有内容压缩在一起:

item_prices = [p for i, n, p in zip(result.values()) if n in item_names]

获得具有相同结构的结果会result更加棘手,涉及更多的压缩和解包,或者需要您检查串列两次。

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *