我在SQL管理工作室中有一个空表,我想填充每个句子的值。该表有3列 - SentId,Word,Count。
我的句子有这样的结构:
sentence = {‘features’: [{}, {}, {}…] , ‘id’: 1234}
- >要填写SentId值,我调用SQL“插入表值(这里为3列提供3个值)”语句,输入句子['id'],返回1234.这很简单。下一步我遇到了问题。
- >要获取Word和Count列的值,我需要进入具有此结构的“features”:
‘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"))
非常感谢帮助我。我是编程新手。
答案 0 :(得分:0)
正如您自己可以看到的那样,句子['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