【问题标题】:return value in a dictionary that's within a list, the whole thing in a dictionary返回列表中字典中的值,字典中的整个内容
【发布时间】:2016-07-29 21:26:46
【问题描述】:

我在 SQL 管理工作室中有一个空表,我想用每个句子的值填充它。该表有 3 列 - SentId、Word、Count。

我的句子结构如下:

sentence = {‘features’: [{}, {}, {}…] , ‘id’: 1234}

-->填写SentId值,我调用SQL“insert into table values(这里为3列提供3个值)”语句,输入sentence['id'],返回1234,很简单。下一步我有问题。

-->要获取 Word 和 Count 列的值,我需要进入具有以下结构的“功能”:

‘features’: [ {‘word’:’ hello’, ‘count’: 2}, {‘word’: ’there’, ‘count’:1}, {}, {}…]

到目前为止我运行了这个:

sentence = {'features': [{'word': 'hello', 'count': 2}, {'word': 'there', 'count':1}] , 'id': 1234}
print(sentence['features'])
    #out>>  [{'word': 'hello', 'count': 2}, {'word': 'there', 'count': 1}]

所以我需要进入列表中的字典。 这不起作用:

print(sentence['features'].get("word"))

非常感谢您帮助我。我是编程新手。

【问题讨论】:

  • 句子['features'][0]['word']
  • 不要用-1标记我;帮帮我吧。谢谢
  • 谢谢!!!!我很快就会删除我的愚蠢问题
  • 啊啊啊。我不能删除它。永远让我感到羞耻。 xD版主请删除它,伙计。谢谢你!

标签: python


【解决方案1】:

您自己可能会看到, sentence['features'] 返回一个列表。不是字典。 为了在 Python 中从列表中获取元素,您需要对其进行索引。

a=[1,2,3]
print(a[0]) #would print 1

所以在你的情况下,这将导致以下代码:

print(sentence['features'][0].get("word"))

sentence['features'][0] 返回第一个字典,然后您在其中返回键 'word' 的值。 如果你想遍历列表中的所有项目,你可以这样做:

for i in sentence['features']:
    print(i['word'])

欲了解更多信息,请参阅:https://docs.python.org/3/tutorial/datastructures.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多