简体   繁体   中英

Python - Getting string from list inside dict

I know this is something purely simple, but I can't wrap my head around it. I want to access the song "Sunrise" in the following dict/list. What's the proper way to do this with Python?

{"Player": 
    {"Playlist": 
        [
            {"Song" : "Foo", "Album" : "Bar"}, 
            {"Song" : "Sunrise", "Album", : "Random"}
        ]
    }
}
d = {"Player": 
    {"Playlist": 
        [
            {"Song" : "Foo", "Album" : "Bar"}, 
            {"Song" : "Sunrise", "Album", "Random"}
        ]
    }
}

for song in d['Player']['PlayList']:
    print song

Prints:

{'Album': 'Bar', 'Song': 'Food'}
{'Album': 'Random', 'Song': 'Sunrise'}

To access an element of a list in a dictionary, in this instance the value Sunrise inside of Song :

for song in d['Player']['Playlist']:
    if song['Song'] is 'Sunrise':
        #do thing with song here
        print song

prints:

{'Album': 'Random', 'Song': 'Sunrise'}

In Python, a Dictionary can contain lots of different types of values for a given key. Breaking down your dictionary, this is what everything actually is:

{"Player":  
    {"Playlist": 
        [
            {"Song" : "Foo", "Album" : "Bar"}, 
            {"Song" : "Sunrise", "Album", "Random"}
        ]
    }
}

d['Player']:

Result : {'Playlist': [{'Album': 'Bar', 'Song': 'Food'}, {'Album': 'Random', 'Song': 'Sunrise'}]}

The Key is a string, the value is a dictionary of playlists.


d['Player']['Playlist']:

Result : {'Playlist': [{'Album': 'Bar', 'Song': 'Food'}, {'Album': 'Random', 'Song': 'Sunrise'}]}

the key is Playlist , the value is a list of dict ionaries.


d['Player']['Playlist'][0]

Result : {'Album': 'Bar', 'Song': 'Food'}

This is a list accessor, it access the first element in the list (in this case, the dict that holds the Album and the Song )


d['Player']['Playlist'][0]['Album']:

Result : 'Bar'

Accesses the value of the dictionary with the key Album inside the first element of the list inside the playlist.


Or, to spell it out if you're a perl guy, you have a dictionary of Player s that has a dictionary of Playlists with a list of dictionaries of songs (song data) inside of it.

如果d是您的字典,则

 d['Player']['Playlist'][1]['Song']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM