我在字典中有以下示例dictionary,如何仅在数据字段中循环和显示键/值。当我运行下面的程序时,我得到了以下错误。不知道我做错了什么。有什么建议吗
in1 = {
"data": {
"id": "1574083",
"username": "snoopdogg",
"full_name": "Snoop Dogg",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
"bio": "This is my bio",
"website": "http://snoopdogg.com",
"counts": {
"media": 1320,
"follows": 420,
"followed_by": 3410
}
}}
print(in1['data']['id'])
for k , v in in1.items():
print("\n RAW DATA:" + k)
u_info = v['username'] + ' ' + v['full_name']
print("Thanks for the info : " + u_info)
for ke,v1 in v.items():
print("Keys ", ke['website'])
print("Keys ", ke['counts'])
我得到的错误是
python3 dictionary_example.py
1574083
RAW DATA:data
Thanks for the info : snoopdogg Snoop Dogg
Traceback (most recent call last):
File "dictionary_example.py", line 24, in <module>
print("Keys ", ke['website'])
TypeError: string indices must be integers
与@Raju answer类似,您可以在不使用循环的情况下获得
['website']
和['counts']
的值,因为它是唯一一个字典(基于您的问题)试试看:
print(in1['data']['id']) print(in1['data']['website']) print(in1['data']['counts'])
您正在打印导致问题的
u_info
内引号。 在代码中,您试图将键k1
用作字典,但它是字符串。 如果要打印website
和counts
值,则无需使用for循环,可以直接使用v['website']
和v['counts']
相关问题 更多 >
编程相关推荐