在列表字典中搜索

时间:2019-06-07 18:29:50

标签: python list dictionary

我正在尝试在列表字典中进行搜索 列表元素是字典

例如,在《纽约时报》的文章或帖子中搜索单词 还是两个报纸的文章中都包含这个词

此外,如何将元素添加到特定词典(报纸)


news_papers ={
    "NY Times": [
        {"id": 1, "language": "English", "edition": "first", "author": "MR Mike",
         "article": "New york post example"}
    ],

    "the POST": [
        {"id": 1, "language": "English", "edition": "first", "author": "kyle",
         "article": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, ...etc"},

        {"id": 2, "language": "English", "edition": "first", "author": "MR Jake",
         "article": "writing for New york"}
    ]

}

预期结果:

如果我搜索“纽约”一词

结果:

1-Ny次,商品ID:1

2-帖子,文章ID:2

2 个答案:

答案 0 :(得分:1)

您需要遍历每个列表并使用字典键来获取所需的内容。您还必须注意区分大小写:

compamy_article_id = []
for company, paper in news_papers.items():
    for article in paper:
        if search_str.lower() in article['article'].lower():
            compamy_article_id.append((company, article['id']))

或单线:

search_str = 'New York'
compamy_article_id = [(company, article['id']) for company, paper in news_papers.items() for article in paper if search_str.lower() in article['article'].lower()]

然后打印:

for company, art_id in compamy_article_id:
    print(f"{index + 1}-{company}, artical id: {art_id}")

输出:

1-NY Times, artical id: 1
2-the POST, artical id: 2

答案 1 :(得分:0)

使用三元运算符:

for key, value in news_papers.items():
    print(f'{ (key, value[0].get("id")) if "new york" in value[0].get("article").lower() else "" }')

其他答案更合适,这只是一个侧边栏。