python - 如何在字典中循环
问题描述
我在字典中有以下示例字典,我如何循环并仅在数据字段中显示键/值。当我运行以下内容时,出现以下错误。不知道我做错了什么。请有任何建议。
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
解决方案
您正在u_info
引起问题的引号内打印。在您的代码中,您尝试将键k1
用作字典,但它是字符串。如果要打印website
和counts
值,则无需使用 for 循环,您可以直接使用v['website']
and v['counts']
。
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("\t" + u_info)
print("Keys ", v['website'])
print("Keys ", v['counts'])
推荐阅读
- javascript - 交叉淡入淡出的图像
- java - Gradle 依赖资源访问
- python - 用每个文件的唯一目录的一部分填充一列?
- ios - 使用 Core Image 自定义滤镜在两个图像之间实现颜色传输
- javascript - jQuery is() 或 has() 在多个元素上
- java - 如何根据 Firebase 中帖子的点赞数对 Android 中 RecyclerView 中的数据进行排序?
- c++ - RVO 在这种情况下会起作用吗?
- c++11 - 使用 C++ Boost 库如何返回自格林威治标准时间 1901 年 1 月 1 日 00:00:00 以来的秒数?
- java - 使用 Apache POI 将 .doc 和 .ppt 文件嵌入到 excel 中并显示其内容
- ios - NavigationController 一个根和两个 ViewController