2016-07-29 83 views
-3

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

我的句子具有这样的结构:

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

- >要填写SentId值,我调用SQL“插入到表中的值(3列在这里提供3个值)”语句,输入语句[ id'],它返回1234.很简单。随着下一步我有问题。

- >要获取字值和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}] 

所以我需要进入列表中的字典。 这didn`t工作:

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

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

+1

句子[“功能”] [0] [“字”] –

+0

唐用-1标记我;反而帮助我。谢谢 – el347

+0

谢谢!!!!我很快会删除我的愚蠢问题 – el347

回答

0

正如你可能看到自己,句子['features']返回一个列表。不是字典。 为了从Python列表中获取元素,您需要为它编制索引。

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

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

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

句子[“功能”] [0]返回第一个字典,在其中,然后在返回值关键'词'。 如果你要循环列表中的所有项目,你可以这样做:

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

如需进一步信息,请参见:https://docs.python.org/3/tutorial/datastructures.html

+0

非常感谢,伙计们!我知道了。祝你今天愉快! ^。^〜 – el347