Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dictionary comprehension
#1
how can i make a dictionary comprehension for the dictionary being built in this code snippet?

aws_regions = [
    ('us-east-1',      'use1', 'N. Virginia'   ),
    ('us-east-2',      'use2', 'Ohio'          ),
    ('us-west-1',      'usw1', 'N. California' ),
    ('us-west-2',      'usw2', 'Oregon'        ),
    ('ca-central-1',   'cac1', 'Central'       ),
    ('eu-west-1',      'euw1', 'Ireland'       ),
    ('eu-west-2',      'euw2', 'London'        ),
    ('eu-central-1',   'euc1', 'Frankfurt'     ),
    ('ap-southeast-1', 'ase1', 'Singapore'     ),
    ('ap-northeast-1', 'ane1', 'Tokyo'         ),
    ('ap-northeast-2', 'ane2', 'Seoul'         ),
    ('ap-southeast-2', 'ase2', 'Sydney'        ),
    ('ap-south-1',     'aps1', 'Mumbai'        ),
    ('sa-east-1',      'sae1', 'Sao Paulo'     ),
]

aws_regions_dict = {}
for r in aws_regions:
    aws_regions_dict[r[0]] = r
    aws_regions_dict[r[1]] = r
this dictionary will have keys from both long names in the first column and short names in the second column.  this is what i don't how to do in comprehsions.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
aws_regions = [
    ('us-east-1',      'use1', 'N. Virginia'   ),
    ('us-east-2',      'use2', 'Ohio'          ),
    ('us-west-1',      'usw1', 'N. California' ),
    ('us-west-2',      'usw2', 'Oregon'        ),
    ('ca-central-1',   'cac1', 'Central'       ),
    ('eu-west-1',      'euw1', 'Ireland'       ),
    ('eu-west-2',      'euw2', 'London'        ),
    ('eu-central-1',   'euc1', 'Frankfurt'     ),
    ('ap-southeast-1', 'ase1', 'Singapore'     ),
    ('ap-northeast-1', 'ane1', 'Tokyo'         ),
    ('ap-northeast-2', 'ane2', 'Seoul'         ),
    ('ap-southeast-2', 'ase2', 'Sydney'        ),
    ('ap-south-1',     'aps1', 'Mumbai'        ),
    ('sa-east-1',      'sae1', 'Sao Paulo'     ),
]

aws_regions_dict = {k:r for r in aws_regions for k in r[:2]}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  dictionary: print key/value with list(dict) comprehension wardancer84 4 2,998 Nov-14-2018, 03:14 PM
Last Post: wardancer84
  Dictionary Comprehension - ValueError: too many values to unpack (expected 2) samRddhi 2 8,500 Dec-22-2017, 09:25 AM
Last Post: samRddhi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020