0
daisy = {
    'type' : 'dog',
    'owner' : 'miranda',
    }

bella = {
    'type' : 'cat',
    'owner' : 'luke',
    }

charlie = {
    'type' : 'lizard',
    'owner' : 'mike',
}

pets = [daisy, bella, ruby]

How to print out only the names of the dictionaries i.e. daisy, bella, charlie from a list?

3 Answers3

1

This is really an xy problem. You should never need to print the names of variables. The reason is that the data structures often get passed around in ways that the names of the variable get lost. This is what happens when you do:

pets = [daisy, bella, ruby]

Here pets is just a list of dictionaries...they are no longer named.

If the name is significant, then it should be part of the data. For example:

daisy = {
    'name': 'Daisy',
    'type': 'dog',
    'owner': 'miranda',
    }

bella = {
    'name': 'Bella',
    'type': 'cat',
    'owner': 'luke',
    }

charlie = {
    'name': 'Charlie',
    'type': 'lizard',
    'owner': 'mike',
}

pets = [daisy, bella, charlie]

for pet in pets:
    print(pet['name'])

Prints:

Daisy
Bella
Charlie

In fact, you can get rid of the named variable altogether now:

pets = [
    {
        'name': 'Daisy',
        'type': 'dog',
        'owner': 'miranda',
    },
    {
        'name': 'Bella',
        'type': 'cat',
        'owner': 'luke',
    },
    {
        'name': 'Charlie',
        'type': 'lizard',
        'owner': 'mike',
    }
]
Mark
  • 90,562
  • 7
  • 108
  • 148
0

You can do it like this:

daisy = {
    'type' : 'dog',
    'owner' : 'miranda',
    }

bella = {
    'type' : 'cat',
    'owner' : 'luke',
    }

ruby = {
    'type' : 'lizard',
    'owner' : 'mike',
}

pets = [daisy, bella, ruby]

for i, e in list(globals().items()):
    if e in pets:
        print(i)
Rob Kwasowski
  • 2,690
  • 3
  • 13
  • 32
0
daisy = {
    'name': 'Daisy',
    'type': 'dog',
    'owner': 'miranda',
    }

bella = {
    'name': 'Bella',
    'type': 'cat',
    'owner': 'luke',
    }

charlie = {
    'name': 'Charlie',
    'type': 'lizard',
    'owner': 'mike',
}

pets = [daisy, bella, charlie]

for i in pets:
    name = i["name"]
    print(name)
Osadhi Virochana
  • 1,294
  • 2
  • 11
  • 21
Aakash Thapa
  • 74
  • 1
  • 7