Home > Back-end >  how to retrieve data from the dictionary
how to retrieve data from the dictionary

Time:05-31

How can I get the phone number and state name of the city of Mooresville from this dictionary I get this dictionary from an sql query

cursor = conn.cursor(as_dict=True)
{'CityName': 'Milton', 'Tel': 623-2891, 'code': '850', 'title': 'FL'}
{'CityName': 'Mooresville', 'Tel': 985-3764, 'code': '765', 'title': 'IN'}
{'CityName': 'Sunnyvale', 'Tel': 730-2231, 'code': '408', 'title': 'CA'}

Tried this

for row in cursor:
       print(row['CityName'])
Milton
Mooresville
Sunnyvale

CodePudding user response:

cities = [{'CityName': 'Milton', 'Tel': 623-2891, 'code': '850', 'title': 'FL'},
        {'CityName': 'Mooresville', 'Tel': 985-3764, 'code': '765', 'title': 'IN'},
        {'CityName': 'Sunnyvale', 'Tel': 730-2231, 'code': '408', 'title': 'CA'}]

search = "Milton" 


for city in cities:
    if(city['CityName']  == search ):
        print(city)

CodePudding user response:

The fetchall() method is returning a list of dictionaries. So first, you need to identify the dictionary with 'CityName': 'Mooresville':

for a in row:
    if a['CityName'] == 'Mooresville':
        break

The break is ther to stop the loop, so the variable a is going to keep the last value it found (the one where 'CityName' is 'Mooresville')

Now, you can just extract the values you want as with any dictionary, i.e.:

print(a['Tel'], a['title'])

An alternative way could be

city_name = 'Mooresville'

try:
  city = [a for a in row if a['CityName'] == city_name ][0]
except:
  print('unknown city')

This will tell you if the city is not in the list. The first version, as you noted in your comment, assumes you are going to search only for a city included in the list.

Note: You may have to look at how fetchall() works, because the tel number is not a string, but a subtraction of two integers.

  • Related