user13780178
user13780178

Reputation:

How to print a dictionary's name?

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?

Upvotes: 0

Views: 1865

Answers (3)

Aakash Thapa
Aakash Thapa

Reputation: 74

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)

Upvotes: 0

Mark
Mark

Reputation: 92440

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

Upvotes: 1

Rob Kwasowski
Rob Kwasowski

Reputation: 2780

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)

Upvotes: 0

Related Questions