flip keys and values in dictionary python

前端 未结 3 1715
难免孤独
难免孤独 2021-01-23 21:25

I have a dictionary called z that looks like this


{0: [0.28209479177387814, 0.19947114020071635, 0.10377687435514868, 0.07338133158686996], -1: [0.282094791773878

3条回答
  •  甜味超标
    2021-01-23 22:18

    Easiest way to flip key value in a dict is using dict comprehension, which looks like this: {value: key for key, value in ORIGINAL_DICT.items()}. Full example:

    REGION_PREFIX = {
        'AB': 'Alberta',
        'BC': 'British Columbia',
        'IN': 'International',
        'MB': 'Manitoba',
        'NB': 'New Brunswick',
        'NL': 'Newfoundland',
        'NS': 'Nova Scotia',
        'NU': 'Nunavut',
        'NW': 'Northwest Territories',
        'ON': 'Ontario',
        'PE': 'Prince Edward Island',
        'QC': 'Quebec',
        'SK': 'Saskatchewan',
        'US': 'United States',
        'YK': 'Yukon',
    }
    
    REGION_PREFIX2 = {value: key for key, value in REGION_PREFIX.items()}
    

    And your output is this:

    {'Alberta': 'AB', 'British Columbia': 'BC', 'International': 'IN', 'Manitoba': 'MB', 'New Brunswick': 'NB', 'Newfoundland': 'NL', 'Nova Scotia': 'NS', 'Nunavut': 'NU', 'Northwest Territories': 'NW', 'Ontario': 'ON', 'Prince Edward Island': 'PE', 'Quebec': 'QC', 'Saskatchewan': 'SK', 'United States': 'US', 'Yukon': 'YK'}
    

    Cheers!

提交回复
热议问题