Python-如果值符合条件,则打印字典元素

时间:2020-02-04 22:56:01

标签: python python-3.x dictionary geocoding

我在过滤字典(OpenCage)中的数据时遇到问题。我故意使用城市名称来尝试将结果范围缩小到仅乡村或城市。以下代码导致1个村庄和5个我不感兴趣的项目。如何设置代码格式,以便仅看到“村庄”?

from opencage.geocoder import OpenCageGeocode

key ="xxx"

geocoder = OpenCageGeocode(key)

query = 'Malmok'

results = geocoder.geocode(query)

for i in results:
    if i['components']['_type'] == "city" or "village":
        print(i['components']['_type'])
    else:
        pass

结果:

village
farm
neighbourhood
road
road
neighbourhood

整个字典有点混乱,但这是一个整体结果:

{'annotations': {'DMS': {'lat': "12° 35' 46.13784'' N", 'lng': "70° 2' 56.16312'' W"}, 'MGRS': '19PCP8606592703', 'Maidenhead': 'FK42xo43db', 'Mercator': {'x': -7797811.686, 'y': 1404318.012}, 'OSM': {'edit_url': 'https://www.openstreetmap.org/edit?node=4599172436#map=16/12.59615/-70.04893', 'note_url': 'https://www.openstreetmap.org/note/new#map=16/12.59615/-70.04893&layers=N', 'url': 'https://www.openstreetmap.org/?mlat=12.59615&mlon=-70.04893#map=16/12.59615/-70.04893'}, 'UN_M49': {'regions': {'AMERICAS': '019', 'AW': '533', 'CARIBBEAN': '029', 'LATIN_AMERICA': '419', 'WORLD': '001'}, 'statistical_groupings': ['LEDC', 'SIDS']}, 'callingcode': 297, 'currency': {'alternate_symbols': ['Afl'], 'decimal_mark': '.', 'html_entity': 'ƒ', 'iso_code': 'AWG', 'iso_numeric': '533', 'name': 'Aruban Florin', 'smallest_denomination': 5, 'subunit': 'Cent', 'subunit_to_unit': 100, 'symbol': 'ƒ', 'symbol_first': 0, 'thousands_separator': ','}, 'flag': '??', 'geohash': 'd6nptvpcvs2vuyw7nzb0', 'qibla': 64.08, 'roadinfo': {'drive_on': 'right', 'speed_in': 'km/h'}, 'sun': {'rise': {'apparent': 1580814360, 'astronomical': 1580810040, 'civil': 1580813040, 'nautical': 1580811540}, 'set': {'apparent': 1580856120, 'astronomical': 1580860440, 'civil': 1580857440, 'nautical': 1580858940}}, 'timezone': {'name': 'America/Curacao', 'now_in_dst': 0, 'offset_sec': -14400, 'offset_string': '-0400', 'short_name': 'AST'}, 'what3words': {'words': 'donate.magistrates.ploy'}}, 'bounds': {'northeast': {'lat': 12.6161494, 'lng': -70.0289342}, 'southwest': {'lat': 12.5761494, 'lng': -70.0689342}}, 'components': {'ISO_3166-1_alpha-2': 'AW', 'ISO_3166-1_alpha-3': 'ABW', '_category': 'place', '_type': 'village', 'continent': 'North America', 'country': 'The Netherlands', 'country_code': 'nl', 'hamlet': 'Malmok', 'postcode': '029'}, 'confidence': 7, 'formatted': '029 Malmok, The Netherlands', 'geometry': {'lat': 12.5961494, 'lng': -70.0489342}}

如果我使用过

type = results[0]['components']['_type']

我只会得到第一个结果。我尝试自动递增并将0替换为x,但没有用。

0 个答案:

没有答案