Searching multiple dictonaries in python

To develop a board game, I have created multiple dictonaries with city names. Each dictonary have some variables. Based on the city name input by player, the program has to search a particular city dictonary and display it’s variable value (Ex: Cost of the city). Please guide me how to search and retrive the required data. Sample dictonaries for cities “bombay” and “Ahmedabad” are as below:

bombay = {
‘id’ : 2,
‘name’ : ‘Bombay’,
‘cost’ : 8500,
‘colour’ : “red”,
‘house_cost’ : 7500,
‘hotel_cost’ : 7500,
‘rent_with_house_0’ : 1200,
‘rent_with_house_1’ : 4000,
‘rent_with_house_2’ : 5500,
‘rent_with_house_3’ : 7500,
‘rent_with_hotel’ : 9000,
}

ahmedabad = {
‘id’ : 5,
‘name’ : ‘Ahmedabad’,
‘cost’ : 4000,
‘colour’ : “red”,
‘house_cost’ : 4500,
‘hotel_cost’ : 4500,
‘rent_with_house_0’ : 400,
‘rent_with_house_1’ : 1500,
‘rent_with_house_2’ : 3000,
‘rent_with_house_3’ : 4200,
‘rent_with_hotel’ : 5000,
}

A simple solution would be to have a dictionary with the city names as keys and the dictionaries with city information as values. If the user is going to type the names you might want to ensure the case is always the same, e.g. by using lower case keys and calling str.lower() on the input.

Thanks for your reply. I already used the lower case function. Since, I am new to python, can you please provide the command/syntax by using kays and values to get the info from multiple dictonaries. If possible, with example code. Thank you,

You can simply chain the index access. For example, let’s assume we already have defined the two ahmedabad and bombay dicts you described above. I can then define a cities dict, and then get the color for Bombay from that:

cities = {'ahmedabad': ahmedabad, 'bombay': bombay}
color = cities['bombay']['color']

Of course you can also use variables instead of literal strings as keys, e.g. if the user entered a city in the variable city and you want to get the cost of that city:

cost = cities[city]['cost']
2 Likes