【问题标题】:Put dict into new list based on a key value in Python根据Python中的键值将dict放入新列表
【发布时间】:2015-02-12 06:06:29
【问题描述】:

我的数据如下所示:

[{'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'}]        

如果“艺术家”键的值 == x,我想将整个 dict 放入一个新列表到目前为止,我的代码只返回一个空白列表。

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

任何帮助将不胜感激!

【问题讨论】:

  • 这是做什么的? self.data_to_dict()
  • 它返回的数据格式类似于上面的内容:[{'album': 'Lonerism', 'song': 'Led Zeppelin (Bonus Track)', 'datetime': '2014-12-10 08:03:00', '艺术家': '驯服黑斑羚'}]

标签: python python-2.7 dictionary append


【解决方案1】:

您正在存储一个方法引用

arts = d['artist'].lower

因为你没有调用方法,你只得到方法对象本身。这永远不会等于pickartist 中的字符串。

添加():

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

演示:

>>> 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

【讨论】:

  • 非常感谢!语法每次都能吸引我。
猜你喜欢
  • 1970-01-01
  • 2021-02-26
  • 2018-03-31
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
  • 2022-06-17
  • 2022-10-07
  • 2022-08-18
相关资源
最近更新 更多