0

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'}]

1 Answer 1

3

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').

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, sir. If I want multiple keys per item, say CreationDate along with ImageId, would I create a set? I'm also unsure how to pull both keys at once? I tried [d['ImageId']['CreationDate']
@RagePwn [(d['ImageId'], d['CreationDate']) for d in ImageDict['Images']] would create a list of tuples like [('ami-0234bd15', '2016-07-05T18:31:48.000Z'), ...etc...].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.