0

I have multiple dictionaries which contain some information, for example:

northLine = {
    'capacity': 100,
    'name': 'Delhi' 
}
eastLine = {
    'capacity': 110,
    'name': 'Rajasthan' 
}
westLine = {
    'capacity': 120,
    'name': 'Orissa' 
}
southLine = {
    'capacity': 130,
    'name': 'J&K' 
}

I have an input list that basically tells us that which line should we use, for example, if it says that [west, north] then it should pick the values from west and north lines only. My code:

northLine = {
    'capacity': 100,
    'name': 'Delhi' 
}
eastLine = {
    'capacity': 110,
    'name': 'Rajasthan' 
}
westLine = {
    'capacity': 120,
    'name': 'Orissa'
}
southLine = {
    'capacity': 130,
    'name': 'J&K' 
}
listOfZone = ['west', 'south']
for i in listOfState:
    print(i+'Line'['name'])

Can somebody please help?

Vesper
  • 795
  • 1
  • 9
  • 21
  • 4
    You should use a dictionary with key `west`, `north` etc that point to the appropriate dicts. – Mark Mar 07 '21 at 18:05
  • 1
    I think @MarkM solution is the best, but if you want you can use `eval`, like so `print(eval(i+"Line")[name])`, [but keep in mind it is considered bad practice](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – gionni Mar 07 '21 at 18:11
  • yes, that's why I have decided to change my method, this can reduce the unnecessary efforts. – Vesper Mar 07 '21 at 18:14

2 Answers2

3

When you need to reference data by a key value, you use a dict. You already did that for each direction. Now you need to do it for your four directions:

line_dict = {
    "north": {
        'capacity': 100,
        'name': 'Delhi' 
    }
    "east": {
        'capacity': 110,
        'name': 'Rajasthan' 
    }
    "west": {
        'capacity': 120,
        'name': 'Orissa'
    }
    "south": {
        'capacity': 130,
        'name': 'J&K' 
    }
}

Now you iterate through your directions, choosing the appropriate dict and the values from the inner dict for each of those directions.

Prune
  • 76,765
  • 14
  • 60
  • 81
2

you can use code below

dict_items = {

    "north": {
        'capacity': 100,
        'name': 'Delhi'
    },
    "east": {
        'capacity': 110,
        'name': 'Rajasthan'
    },
    "west": {
        'capacity': 120,
        'name': 'Orissa'
    },
    "south": {
        'capacity': 130,
        'name': 'J&K'
    }
}

listOfZones = ['north', 'east'] # List of zones
for zone in listOfZones:
    item = dict_items.get(zone)
    if item:
        print(f"Zone Name- {zone}")
        print(dict_items[zone])
George Imerlishvili
  • 1,816
  • 2
  • 12
  • 20