需要python字典循环协助 [英] Need python dictionary loop assistance

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

问题描述

我没有做过很多Python编程,我试图读入一个基本的csv,然后从它创建一个嵌套字典。这是我到目前为止,我似乎有一些问题循环或覆盖我的字典。我知道这不是很有效率。

I have not done a lot of Python programming and am attempting to read in a basic csv then create a nested dictionary from it. Here is what I have so far and I seem to have some issues with looping or overwriting my dict. I know it's not very efficient.

import csv

reader = csv.DictReader(open("fruit.csv"))

fruit_dict = {}
color_dict = {}
for row in reader:
    info_list = []
    count = row.pop('count')
    info_list.append(count)
    year = row.pop('year')
    info_list.append(year)
    info = row.pop('info')
    info_list.append(info)
    if row['color'] not in color_dict:
        #print row['color']
        color_dict['color'] = row['color']
            #print fruit_dict  
        if row['fruit'] not in fruit_dict:
            fruit_dict['name'] = row['fruit']
            #print fruit_dict
            #print info_list
            list_of_info_lists =[]              
            list_of_info_lists.append(info_list)
            fruit_dict['fruitInfo'] = list_of_info_lists
            color_dict['fruit'] = fruit_dict
            #print color_dict
        else:
            list_of_info_lists.append(info_list)
            fruit_dict['fruitInfo'] = list_of_info_lists
            color_dict['fruit'] = fruit_dict
            #print color_dict
    else:
        if row['color'] in color_dict:
            if row['fruit'] not in fruit_dict:
                fruit_dict['name'] = row['fruit']
                #print fruit_dict
                #print info_list
                list_of_info_lists =[]              
                list_of_info_lists.append(info_list)
                fruit_dict['fruitInfo'] = list_of_info_lists
                color_dict['fruit'] = fruit_dict
                #print color_dict
            else:
                list_of_info_lists.append(info_list)
                fruit_dict['fruitInfo'] = list_of_info_lists
                color_dict['fruit'] = fruit_dict
                #print color_dict

#print color_dict

这里是csv:

color,fruit,year,count,info
red,apple,1970,3,good
red,apple,1922,5,okay
orange,orange,1935,2,okay
green,celery,2001,22,marginal
red,cherries,1999,5,outstanding
orange,carrot,1952,7,okay
green,celery,2014,2,good
green,grapes,2001,12,good

我得到的是:

{'color': 'green', 'fruit': {'name': 'grapes', 'fruitInfo': [['12', '2001', 'good']]}}

这是可爱的,除了我期待几行,当'name'已经存在时,期望列表的列表,例如:

Which is lovely except that I am expecting a few more lines than that and am expecting a list of lists when the 'name' already exists for example:

{'color': 'red', 'fruit': {'name': 'apple', 'fruitInfo': [['5', '1922', 'okay'],['3', '1970', 'good']]}}

任何建议都非常感谢。最终的目标是生成一个json文件。

Any advice would be greatly appreciated. The eventual goal is generate a json file.

谢谢,
susan

Thanks, susan

我想要到底:

[{'color': 'red', 'fruit': {'name': 'apple', 'fruitInfo': [['5', '1922', 'okay'],['3', '1970', 'good']]}},
{'color': 'red', 'fruit': {'name': 'cherries', 'fruitInfo': [['5', '1999', 'outstanding']]}},
{'color': 'orange', 'fruit': {'name': 'orange', 'fruitInfo': [['2', '1935', 'okay']]}},
{'color': 'orange', 'fruit': {'name': 'carrot', 'fruitInfo': [['7', '1952', 'okay']]}},
{'color': 'green', 'fruit': {'name': 'celery', 'fruitInfo': [['2', '2014', 'good'],['22', '2001', 'marginal']]}},
{'color': 'green', 'fruit': {'name': 'grapes', 'fruitInfo': [['12', '2001', 'good']]}}]


推荐答案

在处理字典的字典时,我的模式是这样的: / p>

When dealing with dictionaries of dictionaries, my pattern is like this:

sub_dict = main_dict.get(key, {})
sub_dict[sub_key] = sub_value
main_dict[key] = sub_dict

这将获取子字典,或 {} / code>如果它不存在。

This gets the sub-dictionary, or {} if it doesn't exist. Then it assigns a value to the sub-dictionary, and puts the sub-dictionary back into the main dictionary.

fruit_dict = {}
for row in reader:
    # make the info_list
    info_list = [row['count'], row['year'], row['info']]
    # extract color and fruit into variables
    color = row['color']
    fruit = row['fruit']
    # unpack the dictionaries and list
    colors = fruit_dict.get(color, {})
    fruits = colors.get(fruit, {})
    info = fruits.get('info', [])
    # reassemble the list and dictionaries
    info.append(info_list)
    fruits['info'] = info
    colors[fruit] = fruits
    fruit_dict[color] = colors

结果与您的示例稍有不同,但有必要更改它以使用颜色和水果作为键。

The result is a little different than your example, but it's necessary to change it to use the color and fruit as keys.


{'orange':{'orange':{'info':[['2','1935','okay']]},'carrot ':{'info':[['22','2001','''''')边缘'],['''''''''''''''''' :{'cherries':{'info':[['5','1999','outstanding']],'apple':{'info':[['3','1970' ],['5','1922','okay']]}}}

{'orange': {'orange': {'info': [['2', '1935', 'okay']]}, 'carrot': {'info': [['7', '1952', 'okay']]}}, 'green': {'celery': {'info': [['22', '2001', 'marginal'], ['2', '2014', 'good']]}, 'grapes': {'info': [['12', '2001', 'good']]}}, 'red': {'cherries': {'info': [['5', '1999', 'outstanding']]}, 'apple': {'info': [['3', '1970', 'good'], ['5', '1922', 'okay']]}}}

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

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