Catherine
Catherine

Reputation: 747

Python: Set a list as the value in a dictionary

I have a list of column titles:

column_names = ['','column1', 'column2', 'column3']

I am trying to create a dictionary to store the max and min values of each column. I have the max/min values but I am having trouble successfully creating the dictionary in a manner like:

    {
        'csvfile1' :[{

            "column1": [{
                "max": "154790"
                "min": "134070"
                }],
            "column2": [{
                "max": "148686"
                "min": "125753"
                }],
            "column3": [{
                "max": "80591"
                "min": "40644"
                }]
            }]
    }

Here is my script so far:

    max_min_data={}
    max_min_data['name'] = defaultdict(column_names[1:])

    for number in range(1,3):

        max_min_data[name][column_names[number]]['max']=max_value
        max_min_data[name][column_names[number]]['min']=min_value

This is not working for me, could someone explain why or what I should do to create a structure I described above?

I get the error:

KeyError: 'column1'

I have previously tried:

max_min_data='name'
for number in range(1,3):
   max_min_data[name]=[column_names[number]]

But this only gave a key for the 'column3' not all 3 column names

Upvotes: 0

Views: 82

Answers (2)

SparkAndShine
SparkAndShine

Reputation: 18007

Use a nested dictionary by implementaing the perl's autovivification feature,

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value​

# Store data
max_min_data = AutoVivification()
for number in range(1,3):
    max_min_data[name][column_names[number]]['max']=max_value
    max_min_data[name][column_names[number]]['min']=min_value

Upvotes: 2

glls
glls

Reputation: 2403

as per https://docs.python.org/2/tutorial/datastructures.html

to create a dictionary key:value you must do the following

dictionary[key] = value

you cannot do dictionary[key1][key2][key3] = value

additionally, i do not see your dictionary declared

dictionary= {}

Upvotes: 0

Related Questions