python - 如何访问Python列表中字典中的项目?

标签 python python-3.x python-2.7

我在数据框中有一列,每一行都是一个列表,它是许多具有相同键的字典的集合。我想从字典中的同一个键获取所有项目。

我有这个列表:

s = [{'category': 'Public',
      'name': 'Newspaper',
      'person': 'A'},

     {'category': 'Music',
      'name': 'Andre',
      'person': 'B'},

     {'category': 'Music',
      'name': 'Indian',
      'person': 'A'},

     {'category': 'Artist',
      'name': 'Rihe',
      'person': 'D'},

     {'category': 'Interest',
      'name': 'Sport',
      'person': 'B'}]

我尝试过使用循环和 itemgetter,但由于数据量很大,需要花费很多时间。我正在寻找一种更有效的方法来做到这一点。

from operator import itemgetter 
   category = []
   name_page = []
   getter_category = itemgetter('category')
   getter_name = itemgetter('name')     
   for element  in s:        
      name_page.append(getter_name(element))
      category.append(getter_category(element))

我想要更有效的东西,例如:

s['category'] = ['Public','Music','Music','Artist','Interest']
s['name'] = ['Newspaper','Andre','Indian','Rihe','Sport']
s['person'] = ['A','B','A','D','B']

最佳答案

使用集合中的defaultdict

from collections import defaultdict
o = defaultdict(list)
for ss in s:
    for k, v in ss.items():
        o[k] += [v]

print(dict(o))
Out[7]:
{'category': ['Public', 'Music', 'Music', 'Artist', 'Interest'],
 'name': ['Newspaper', 'Andre', 'Indian', 'Rihe', 'Sport'],
 'person': ['A', 'B', 'A', 'D', 'B']}

关于python - 如何访问Python列表中字典中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56140507/

相关文章:

python - 缓慢的 Python 套接字传输

python - 如何在 Python 中创建基于单击 RadioButton 的循环

python - 将 locust 与 pytest 结合使用

python-3.x - 将 .TIF 转换为 .PDF 得到 PIL : Error reading image

python-3.x - 在python中创建从a到b的整数列表

python - 在python中的字符串中查找unicodes的所有匹配项

.net - IronPython 无法运行导入 numpy 的脚本

python - 使用python将特殊值粘贴到另一个多个excel文件

Python通过两种不同的方法构建列表

python - 如何在 Python 的 for 循环中删除列表元素?