sukhvir
sukhvir

Reputation: 5565

accessing values of a dictionary with duplicate keys

I have a dictionary that looks like this:

reply = {icon:[{name:whatever,url:logo1.png},{name:whatever,url:logo2.png}]}

how do i access logo1.png ?

I tried :

print reply[icon][url]

and it gives me a error:

list indices must be integers, not str

EDIT:

Bear in mind sometimes my dictionary changes to this :

reply = {icon:{name:whatever,url:logo1.png}}

I need a general solution which will work for both kinds of dictionaries

EDIT2: My solution was like this :

    try:
        icon = reply['icon']['url']
        print icon
    except Exception:
        icon = reply['icon'][0]['url']
        print ipshit,icon

This works but looks horrible. I was wondering if there was an easier way than this

Upvotes: 0

Views: 83

Answers (3)

Don
Don

Reputation: 17616

Not so different, but maybe it looks better (KeyError gives finer control):

icon_data = reply['icon']
try:
    icon = icon_data['url']
    print icon
except KeyError:
    icon = icon_data[0]['url']
    print ipshit,icon

or:

icon_data = reply['icon']
if isinstance(icon_data, list):
    icon_data = icon_data[0]
icon = icon_data['url']

Upvotes: 0

ComputerFellow
ComputerFellow

Reputation: 12108

Have you tried this?

reply[icon][0][url]

If you know for sure all the different kinds of responses that you will get, you'll have to write a parser where you're explicitly checking if the values are lists or dicts.

You could try this if it is only the two possibilities that you've described:

def get_icon_url(reply):
    return reply['icon'][0]['url']\
    if type(reply['icon']) is list else reply['icon']['url']

Upvotes: 2

Chris Robak
Chris Robak

Reputation: 118

so in this case, icon is the key to a list, that has two dictionaries with two key / value pairs in each. Also, it looks like you might want want your keys to be strings (icon = 'icon', name='name').. but perhaps they are variables in which case disregard, i'm going to use strings below because it seems the most correct

so:

reply['icon'] # is equal to a list: []
reply['icon'][0] # is equal to a dictionary: {}
reply['icon'][0]['name'] # is equal to 'whatever'
reply['icon'][0]['url'] # is equal to 'logo1.png'
reply['icon'][1] # is equal to the second dictionary: {}
reply['icon'][1]['name'] # is equal to 'whatever'
reply['icon'][1]['url'] # is equal to 'logo2.png'

you can access elements of those inner dictionaries by either knowing how many items are in the list, and reference theme explicitly as done above, or you can iterating through them:

for picture_dict in reply['icon']:
    name = picture_dict['name'] # is equal to 'whatever' on both iterations
    url = picture_dict['url'] #is 'logo1.png' on first iteration, 'logo2.png' on second.

Cheers!

Upvotes: 2

Related Questions