mo_shun
mo_shun

Reputation: 315

Put dict into new list based on a key value in Python

I have data that looks like this:

[{'album': 'Lonerism', 
  'song': 'Led Zeppelin (Bonus Track)', 
  'datetime': '2014-12-10 08:03:00', 
  'artist': 'Tame Impala'}, 
 {'album': 'Lonerism', 
  'song': 'Feels Like We Only Go Backwards', 
  'datetime': '2014-12-10 08:00:00', 
  'artist': 'Tame Impala'}, 
 {'album': 'The Suburbs', 
  'song': 'Empty Room', 
  'datetime': '2014-12-10 07:57:00', 
  'artist': 'Arcade Fire'}]        

If the value for the 'artist' key == x, I want to put the whole dict into a new list So far, my code returns only a blank list.

def Pick_Artist(self, pickartist):
    entries = self.data_to_dict()

    info = []

    for d in entries:
        arts = d['artist'].lower
        if arts == pickartist:
            info.append(d)
        return info

Any help would be most appreciated!!

Upvotes: 0

Views: 300

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122132

You are storing a method reference:

arts = d['artist'].lower

Because you didn't call the method, you only get the method object itself. That'll never be equal to the string in pickartist.

Add ():

arts = d['artist'].lower()

Demo:

>>> d = {'album': 'Lonerism', 'song': 'Led Zeppelin (Bonus Track)', 'datetime': '2014-12-10 08:03:00', 'artist': 'Tame Impala'}
>>> d['artist'].lower
<built-in method lower of str object at 0x106506e70>
>>> d['artist'].lower == 'tame impala'
False
>>> d['artist'].lower()
'tame impala'
>>> d['artist'].lower() == 'tame impala'
True

Upvotes: 4

Related Questions