RagePwn
RagePwn

Reputation: 421

Access Elements in a Python List of Dictionaries

I'm working with a dictionary with structure shown below. It is a dictionary containing two keys, with a list of dictionaries as the value for the key, Images. I can return all data I was to search through with

ImageDict['Images']

I want to create a list of all ImageId values, but I'm not sure how to go about that, given the nested structures.

{'Images': [{'Architecture': 'x86_64',
   'BlockDeviceMappings': [{'DeviceName': '/dev/sda1',
     'Ebs': {'DeleteOnTermination': True,
      'Encrypted': False,
      'SnapshotId': 'snap-635c1b80',
      'VolumeSize': 80,
      'VolumeType': 'gp2'}}],
   'CreationDate': '2016-07-05T18:31:48.000Z',
   'Description': 'tableau dw',
   'Hypervisor': 'xen',
   'ImageId': 'ami-0234bd15',
   'ImageLocation': '15664665456/My-AMI',
   'ImageType': 'machine',
   'Name': 'My-AMI',
   'OwnerId': '15664665456',
   'Platform': 'linux',
   'Public': False,
   'RootDeviceName': '/dev/sda1',
   'RootDeviceType': 'ebs',
   'SriovNetSupport': 'simple',
   'State': 'available',
   'VirtualizationType': 'hvm'},
  {'Architecture': 'x86_64',
   'BlockDeviceMappings': [{'DeviceName': '/dev/sda1',
     'Ebs': {'DeleteOnTermination': True,
      'Encrypted': False,
      'SnapshotId': 'snap-551337ca',
      'VolumeSize': 30,
      'VolumeType': 'gp2'}},
    {'DeviceName': 'xvdca', 'VirtualName': 'ephemeral0'},
    {'DeviceName': 'xvdf',
     'Ebs': {'DeleteOnTermination': False,
      'Encrypted': False,
      'SnapshotId': 'snap-60116dd7',
      'VolumeSize': 300,
      'VolumeType': 'gp2'}}],
   'CreationDate': '2016-11-18T20:16:12.000Z',
   'Description': '',
   'Hypervisor': 'xen',
   'ImageId': 'ami-0aa4911d',
   'ImageLocation': '81643435666912741/cm-test',
   'ImageType': 'machine',
   'Name': 'cm-test',
   'OwnerId': '8164228989741',
   'Platform': 'windows',
   'Public': False,
   'RootDeviceName': '/dev/sda1',
   'RootDeviceType': 'ebs',
   'SriovNetSupport': 'simple',
   'State': 'available',
   'VirtualizationType': 'hvm'}]

Upvotes: 0

Views: 49

Answers (1)

mVChr
mVChr

Reputation: 50185

You can do it with a list comprehension:

image_ids = [d.get('ImageId') for d in ImageDict['Images']]

If you're sure every dict has an ImageId it's more efficient to do d['ImageId'] instead of d.get('ImageId').

Upvotes: 3

Related Questions