字典中的多个值python [英] multiple values in a dictionary python

查看:149
本文介绍了字典中的多个值python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的数据(保存在列表中)

I have data in following form (saved in a list)

id, price, date, category

现在,我基本上是要根据类别分开项目。
基本上是一个字典,其中key是类别和其余的东西(id,price,data)是它的值
我已经创建了一个数据结构,所以让datastructre'item'具有上述四个属性(id,price,date,category)
所以基本上我想要的是以下格式的字典:

Now, I basically want to seperate items based on the category.. basically a dictionary where key is the category and rest of the stuff (id, price, data) are its values I have already created a datastructure so lets a datastructre 'item' has the above four stated attributes (id, price, date, category) So basically what i want is a dictionary in following form:

{1: [item_1,item_2....], 2:[item....]} 

我该怎么办..
由于单个键中有许多值,所以我知道它将使用defaultdict ..但是我仍然无法解决这个问题。
谢谢

how do i do this.. Since there are many values in a single key hence i know that it will use defaultdict.. but still I am not able to get around this. Thanks

推荐答案

我想你想要这样的东西,假设你的当前数据存储在列表 list_data

I think you want something like this, assuming your current data is stored in the list list_data:

dict_data = defaultdict(list)
for item in list_data:
    dict_data[item.category].append(item)

如果每个项目都是元组而不是一个对象,使用 item [3] 而不是 item.category

If each item is a tuple instead of an object, use item[3] instead of item.category.

这篇关于字典中的多个值python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆