ddevalco ddevalco - 1 year ago 120
Python Question

Defining a variable in python from dictionary keys?

I'm struggling with my understanding of lists vs. dictionaries and the best uses of each as well as how to handle the data as I'm trying to learn.

For instance, I have the following data in a CSV file:


I created a dictionary out of it by doing the following:

import csv
reader = csv.DictReader(open('fexmap2.csv'))
fexdata = {}
for row in reader:
for column, value in row.iteritems():
fexdata.setdefault(column, []).append(value)

Now I can print out my dictionary as follows:

{'device': ['2248_1', '2248_2', '2248_3'], 'fexprefix': ['Eth101/1/', 'Eth102/1/', 'Eth103/1/'], 'parent': ['5548_1', '5548_2', '5548_3']}

I can see my keys:

['device', 'fexprefix', 'parent']

So far so good I suppose.

But now I need to do lookups against this data to derive new variables (hope that's the right term).

For instance, I will be parsing some JSON data where I will learn about the device "2248_1".

From that, I need to look up what it's parent is in the dictionary to create a variable I can start to use in the script.

Let's say when I get that "2248_1" from JSON it is defined as:

destdevice = 2248_1

So now I want to say something like this in layman's terms:

if destdevice is found in fexdata['device']
then deviceparent = fexdata['parent'] of fexdata['device']

At which point,
deviceparent = 5548_1

Answer Source

If the device is to be used as a key, make it the key of your dictionary:

fexdata = {}
for row in reader:
    fexdata[row['device']] = row

You can then directly get the parentid of device with id 2248_1:

destdevice = '2248_1'
deviceparent = fexdata[destdevice]['parent']