Aaron
Aaron

Reputation: 77

Python 3 troubles with dictionary and list

I need to get index (number) of item in list, which contains a string c = "Return To Sender (Matrey Remix)". Then get information from this index. But I got numbers of all items in list. No errors

demo = json.loads(raw)
c = "Return To Sender (Matrey Remix)"
for i in (i for i, tr in enumerate(demo['tracks']) if str(tr['title']).find(c)):
    print(i)
dict = demo['tracks'][i]

For example I have 7 track titles in result of code:

for tr in demo['tracks']:
    print(tr['title'])

Track titles:

Return To Sender (Original Mix)
Return To Sender (Matrey Remix)
Return To Sender (Matrey Remix)
Return To Sender (Matrey Remix)
Return To Sender (Original Mix)
Return To Sender (Original Mix)
Return To Sender (Original Mix)

But output is empty

The demo object:

{
    'mixes': [],
    'packs': [],
    'stems': [],
    'tracks': [{
        'id': 7407969,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Original Mix)',
    }, {
        'id': 7407971,
        'mix': 'Matrey Remix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Matrey Remix)',
    }, {
        'id': 9011142,
        'mix': 'Matrey Remix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Matrey Remix)',
    }, {
        'id': 7846774,
        'mix': 'Matrey Remix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Matrey Remix)',
    }, {
        'id': 7407969,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Original Mix)',
    }, {
        'id': 9011141,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'type': 'track',
    }, {
        'id': 7789328,
        'mix': 'Original Mix',
        'name': 'Return To Sender',
        'title': 'Return To Sender (Original Mix)',
    }]
}

Upvotes: 0

Views: 62

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123240

str.find() returns 0 when the text is found at the start:

>>> 'foo bar'.find('foo')
0

That is considered a false value in a boolean context:

>>> if 0:
...     print('Found at position 0!')
...
>>>

If the text is not there, str.find() returns -1 instead. From the str.find() documentation:

Return the lowest index in the string where substring sub is found [...]. Return -1 if sub is not found.

This means that only if the text is at the start will your code not print anything. In all other cases (including not finding the title), the tracks will be printed.

Don't use str.find(). Use in to get True if the text is there, False if it is not:

for i in (i for i, tr in enumerate(demo['tracks']) if c in tr['title']):

Demo using your json data:

>>> c = "Return To Sender (Matrey Remix)"
>>> for i in (i for i, tr in enumerate(demo['tracks']) if c in tr['title']):
...     print(i)
...
1
2
3

Upvotes: 5

Related Questions