Python variable definition from dictionary keys?

I struggle with my understanding of lists and dictionaries and the best uses of each, as well as how to process data as I try to learn.

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

device,parent,fexprefix
2248_1,5548_1,Eth101/1/
2248_2,5548_2,Eth102/1/
2248_3,5548_3,Eth103/1/

I created a dictionary from 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 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 see my keys:

>>>fexdata.keys()
['device', 'fexprefix', 'parent']

So far so good, I suppose.

But now I need to do a search on this data to get new variables (I hope the right term).

For example, I will parse some JSON data, where I find out about the device "2248_1" .

From this, I need to see that it is parent in the dictionary in order to create a variable that I can start using in the script.

, "2248_1" JSON, :

destdevice = 2248_1

, - :

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

deviceparent = 5548_1

+4
3

, :

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

2248_1:

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

, , . :

if destdevice in fexdata['device']:
    parentindex = fexdata['device'].index(destdevice)
    deviceparent = fexdata['parent'][parentindex]

, , , - , , , , ( ) .

:

>>> fexdata = {'device': ['2248_1', '2248_2', '2248_3'], 'fexprefix': ['Eth101/1/', 'Eth102/1/', 'Eth103/1/'], 'parent': ['5548_1', '5548_2', '5548_3']}
>>> destdevice = '2248_1'
>>> if destdevice in fexdata['device']:
...     parentindex = fexdata['device'].index(destdevice)
...     deviceparent = fexdata['parent'][parentindex]
...
>>> deviceparent
'5548_1'
+1

, , , . , "".

.

, :

import csv
reader = csv.DictReader(open('fexmap2.csv'))
fexdata = {}
for row in reader:
    fexdata[row['device']] = row

, , dict:

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

:

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

print deviceparent
5548_1
print fexprefix
Eth101/1/

, , , . , - script.

0

Source: https://habr.com/ru/post/1661854/


All Articles