KeyError访问嵌套字典中的数据

时间:2019-12-03 03:21:27

标签: python arrays python-3.x

我有以下Python脚本:

lista_contatos = {
    "1": {"nome": "Paul", "cel": "+9999999999", "cidade": "SP", "id_cidade": "449139"},
    "2": {"nome": "Junior", "cel": "+999999999", "cidade": "SP", "id_cidade": "449139"}

}
n = len(lista_contatos)
i = int
i = 1
print(n)

while i <= n:
    print(i)
    print(lista_contatos[i]['nome'])
    print(lista_contatos[i]['cel'])
    i = i + 1

我面临的问题是我需要先打印每个键的所有数据,然后再进行第二个数组打印。

问题是,当我将计数器i添加为打印键时,出现错误。

有任何帮助如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

这种数据结构没有多大意义。如果您的键只是连续数字,并且您计划迭代元素,那么字典是错误的工具。正是出于您的预期目的发明了Lists(或tuples,如果需要不可变性),则遍历连续的内存块比散列要高效且语义上合适。

此外,for循环是遍历列表的正确结构,而不是while循环,当停止条件不是计数器时,则更合适。

lista_contatos = [
    {"nome": "Paul", "cel": "+9999999999", "cidade": "SP", "id_cidade": "449139"},
    {"nome": "Junior", "cel": "+999999999", "cidade": "SP", "id_cidade": "449139"}
]

for elem in lista_contatos:
    print(elem['nome'], elem['cel'])

对于您的原始问题,由于整数是字典键的非法值,因此{"1": "foo"}[1]会生成KeyError。您需要将i转换为字符串

lista_contatos[str(i)]['cel']
#              ^^^^^^

这应该感觉像是在跳个圈,这是一个危险信号,表明数据结构的选择出现了问题。

并不是说遍历字典并不是一件好事,但是它的工作方式是使用some_dict.items()some_dict.keys()或{{1 }}。如果您使用的Python <3.6,则不能保证排序(使用some_dict.values())。像collections.OrderedDict这样的计数器在任何情况下都不会输入图片。

i的意图可能是声明一个类型。但这是变量i = int的别名,别名int是用于转换的内置类型。您不需要像这样在Python中声明类型;只需编写i,Python就会自动知道它是一个整数:

i = 1

何时实际使用字典?答案是,当您需要在键值对的基础上快速查找相关项目时,键是一些唯一的,可哈希的标识符,而不是>>> i = 1 >>> type(i) <class 'int'> 中的连续整数。想象一下一个产品库存,每个产品都有一些任意的UPC或SKU编号作为键,而其余产品数据则作为属性的指标。

答案 1 :(得分:0)

基本上,您需要进行DFS打印。

2019-12-03 10:21:12.531 13075-13154/com.example.newlogin D/OkHttp: <br />
2019-12-03 10:21:12.531 13075-13154/com.example.newlogin D/OkHttp: <b>Fatal error</b>:  Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\api\DBFunction.php:88
2019-12-03 10:21:12.531 13075-13154/com.example.newlogin D/OkHttp: Stack trace:
2019-12-03 10:21:12.531 13075-13154/com.example.newlogin D/OkHttp: #0 C:\xampp\htdocs\api\login.php(14): DBFunction-&gt;getUserByEmailAndPassword('admin@admin.com', 'admin')
2019-12-03 10:21:12.531 13075-13154/com.example.newlogin D/OkHttp: #1 {main}
2019-12-03 10:21:12.531 13075-13154/com.example.newlogin D/OkHttp:   thrown in <b>C:\xampp\htdocs\api\DBFunction.php</b> on line <b>88</b><br />
2019-12-03 10:21:12.531 13075-13154/com.example.newlogin D/OkHttp: <-- END HTTP (337-byte body)
2019-12-03 10:21:12.532 1793-6054/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 2252800
2019-12-03 10:21:12.563 1793-6054/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 2252800
2019-12-03 10:21:12.575 13075-13127/com.example.newlogin D/EGL_emulation: eglMakeCurrent: 0xf007fd00: ver 3 1 (tinfo 0xf00c02c0)
2019-12-03 10:21:12.579 1793-6054/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 2252800
2019-12-03 10:21:12.645 13075-13127/com.example.newlogin D/EGL_emulation: eglMakeCurrent: 0xf007fd00: ver 3 1 (tinfo 0xf00c02c0)
2019-12-03 10:21:12.674 2135-6922/system_process W/AppOps: Noting op not finished: uid 10100 pkg com.google.android.gms code 41 time=1575343266660 duration=0
2019-12-03 10:21:12.785 13075-13127/com.example.newlogin I/chatty: uid=10142(com.example.newlogin) RenderThread identical 3 lines
2019-12-03 10:21:12.798 13075-13127/com.example.newlogin D/EGL_emulation: eglMakeCurrent: 0xf007fd00: ver 3 1 (tinfo 0xf00c02c0)
2019-12-03 10:21:12.804 2135-7184/system_process E/InputDispatcher: Window handle Window{579d915 u0 com.example.newlogin/com.example.DBLogin.LoginActivity} has no registered input channel
2019-12-03 10:21:12.825 2135-7184/system_process E/InputDispatcher: Window handle Window{579d915 u0 com.example.newlogin/com.example.DBLogin.LoginActivity} has no registered input channel
2019-12-03 10:21:12.826 13075-13127/com.example.newlogin D/EGL_emulation: eglMakeCurrent: 0xf007fd00: ver 3 1 (tinfo 0xf00c02c0)
2019-12-03 10:21:12.831 13075-13075/com.example.newlogin W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

结果:

lista_contatos = {"1": {"nome": "Paul", "cel": "+9999999999", "cidade": "SP", "id_cidade": "449139"},
                "2": {"nome": "Junior", "cel": "+999999999", "cidade": "SP", "id_cidade": "449139"}}

def printDict(d):
    for k, v in d.items():
        print('key: ', k)
        if type(v) is dict:
            printDict(v)
        else:
            print('value: ', v)
printDict(lista_contatos)