簡體   English   中英

在具有多個值的 python 中的字典中切換鍵和值

[英]Switching keys and values in a dictionary in python with multiple values

給定這樣的字典(來自 geonamescache 的數據):

{'3041563': {'geonameid': 3041563,
  'name': 'Andorra la Vella',
  'latitude': 42.50779,
  'longitude': 1.52109,
  'countrycode': 'AD',
  'population': 20430,
  'timezone': 'Europe/Andorra',
  'admin1code': '07'},
 '290594': {'geonameid': 290594,
  'name': 'Umm Al Quwain City',
  'latitude': 25.56473,
  'longitude': 55.55517,
  'countrycode': 'AE',
  'population': 62747,
  'timezone': 'Asia/Dubai',
  'admin1code': '07'},
 '291074': {'geonameid': 291074,
  'name': 'Ras Al Khaimah City',
  'latitude': 25.78953,
  'longitude': 55.9432,
  'countrycode': 'AE',
  'population': 351943,
  'timezone': 'Asia/Dubai',
  'admin1code': '05'},....

如何為dict中的所有項目切換值為'name'的鍵? 這意味着城市名稱將成為每個項目的關鍵。

預期 output:

{'Andorra la Vella': {'geonameid': 3041563,
  'latitude': 42.50779,
  'longitude': 1.52109,
  'countrycode': 'AD',
  'population': 20430,
  'timezone': 'Europe/Andorra',
  'admin1code': '07'},
 'Umm Al Quwain City': {'geonameid': 290594,
  'latitude': 25.56473,
  'longitude': 55.55517,
  'countrycode': 'AE',
  'population': 62747,
  'timezone': 'Asia/Dubai',
  'admin1code': '07'},
 'Ras Al Khaimah City': {'geonameid': 291074,
  'latitude': 25.78953,
  'longitude': 55.9432,
  'countrycode': 'AE',
  'population': 351943,
  'timezone': 'Asia/Dubai',
  'admin1code': '05'},....

您是否正在尋找這樣的 output?

{'Andorra la Vella': {'admin1code': '07',
  'countrycode': 'AD',
  'geonameid': 3041563,
  'latitude': 42.50779,
  'longitude': 1.52109,
  'name': 'Andorra la Vella',
  'population': 20430,
  'timezone': 'Europe/Andorra'},
 'Ras Al Khaimah City': {'admin1code': '05',
  'countrycode': 'AE',
  'geonameid': 291074,
  'latitude': 25.78953,
  'longitude': 55.9432,
  'name': 'Ras Al Khaimah City',
  'population': 351943,
  'timezone': 'Asia/Dubai'},
 'Umm Al Quwain City': {'admin1code': '07',
  'countrycode': 'AE',
  'geonameid': 290594,
  'latitude': 25.56473,
  'longitude': 55.55517,
  'name': 'Umm Al Quwain City',
  'population': 62747,
  'timezone': 'Asia/Dubai'}}

如果是這樣,您可以從現有字典創建此格式的新字典。 這是您可以做到的一種方法,其中dicc是您現有的字典。

newdic = {}
for key, val in dicc.items():
    newdic[val['name']] = val

print(newdic)

只需將值重新分配為鍵:

data = ...  # Your data here
for geocode, area in data.items():
    cityname = area["name"]
    area[cityname] = "name"
    del area["name"]  # if you don’t want the ‘name’ key anymore
    data[geocode] = area

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM