【问题标题】:how to select the dictionary according to the inputs in python?如何根据python中的输入选择字典?
【发布时间】:2021-03-07 18:04:06
【问题描述】:

我有多个包含一些信息的字典,例如:

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

我有一个输入列表,它基本上告诉我们应该使用哪一行,例如,如果它说[west, north],那么它应该只从westnorth 行中选择值。 我的代码:

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'])

有人可以帮忙吗?

【问题讨论】:

  • 您应该使用带有键 westnorth 等指向适当字典的字典。
  • 我认为@MarkM 解决方案是最好的,但如果你愿意,你可以使用eval,比如print(eval(i+"Line")[name])but keep in mind it is considered bad practice
  • 是的,所以我决定改变我的方法,这样可以减少不必要的工作。

标签: python string dictionary


【解决方案1】:

当您需要通过键值引用数据时,您使用字典。您已经为每个方向都这样做了。现在你需要为你的四个方向去做:

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

现在您遍历您的方向,为每个方向选择适当的字典和内部字典中的值。

【讨论】:

    【解决方案2】:

    你可以使用下面的代码

    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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-07
      • 2021-01-26
      • 1970-01-01
      • 2021-02-28
      • 2021-07-28
      • 2023-01-27
      • 2017-04-17
      • 2022-07-29
      相关资源
      最近更新 更多