Python 使用列表值在字典上迭代

Python 使用列表值在字典上迭代,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,我有一个字典,其中一个是键/值,这个值是一个列表。我试图迭代这个dict来删除特殊字符(这是可以的部分),但是当我得到这个值(这是一个列表)时,我不知道怎么做 这是我的格言: { "id_pessoa_ies": "3", "cpf": "string", "nome": "TESTE COM Ç E ESPACO E É", "nome_social

我有一个字典,其中一个是键/值,这个值是一个列表。我试图迭代这个dict来删除特殊字符(这是可以的部分),但是当我得到这个值(这是一个列表)时,我不知道怎么做

这是我的格言:

{
  "id_pessoa_ies": "3",
  "cpf": "string",
  "nome": "TESTE COM Ç E ESPACO E É",
  "nome_social": "string",
  "sexo": "string",
  "data_nascimento": "26-11-2020",
  "cor_raca": "Preta",
  "estado_civil": "Test word here",
  "municipio_naturalidade": "Test again",
  "uf_naturalidade": "TEST",
  "pais_nascimento": "string",
  "docente_pessoa": [
    {
      "id_docente_ies": "string",
      "matricula": "123456789",
      "titulacao": "TEST",
      "ano_ingresso": "2020",
      "tipo_contrato": "string",
      "tipo_vinculo": "TESTE COM Ç E ESPACO E É ARROBA @ #",
      "id_unidade_lotacao": "1",
      "situacao": "ACTIVATE"
    }
  ]
}
这就是我目前所做的:

for key, value in mydict.items():
       if key == 'docente_pessoa':
           # what should I do here to iterate over 'docente_pessoa' to get it's values and
           # apply my function 'text_to_it()' on it?
       else:
           text = text_to_id(value)
           mydict.items[key] = text
谢谢你的帮助


谢谢你

因为这是一个列表,里面有一个
dict
,你可以这样把它拿出来:

docente_pessoa_dict = value[0]
现在你有了一组新的值,我想你必须改变,所以你可以这样做:

for key, value in docente_pessoa_dict.items():
    # do stuff with key and value
总而言之:

for key, value in mydict.items():
       if key == 'docente_pessoa':
           docente_pessoa_dict = value[0]
           for key, value in docente_pessoa_dict.items():
               # do stuff with key and value
       else:
           # do stuff with key and value
由于发布的代码给出了一个
运行时错误:dictionary在迭代期间更改了大小
,因为您在迭代
dict
时更改了值,这与此问题完全无关,因此您必须找到一种方法来复制键,然后更改值

您只需将
dict
转换为
list
,然后更改
值即可:

for key in list(mydict):
    if key == 'docente_pessoa':
        docente_pessoa_dict = mydict[key][0]
        for docente_pessoa_dict_key, docente_pessoa_dict_value in docente_pessoa_dict.items():
            text = text_to_id(docente_pessoa_dict_value)
            mydict[key][0][docente_pessoa_dict_key] = text 
    else:
        text = text_to_id(mydict[key])
        mydict[key] = text

对于docente\u键,value.items()中的docente\u val:
您可以随意命名变量。基本上,您已经做了相同的事情,但是变量名不同。此外,由于字典是可变的,您只需执行
val=text\u to\u id(val)
,它应该具有相同的效果。嘿@Tim谢谢您的回答。我尝试了你所说的,我得到了:
对于docente\u键,docente\u val in value:ValueError:太多的值无法解压缩(预期为2)
。你知道会是什么吗?是的,我更新了第一条评论,应该是。。。在value.items()中:
您已经有了代码,只需使用不同的变量名再次执行即可。循环中的循环。谢谢你的帮助。我在xxxx处得到了这个错误
运行时错误,在迭代过程中字典的大小发生了变化
。当我添加mydict以更新内部的值时。“你知道可能是什么吗?”Guillhermeshults好吧,这不是你问题的一部分,但看看这个,我会更新答案,以说明你的帮助。我会看一看的。@Guillhermeschults给你,我用正确的方法更新了答案,让我知道它对你是否有效you@GuilhermeSchults我只是修复了代码,因为它没有改变
docente\u pessoa\u dict\u键的值,我现在就修复了它,如果我理解正确,它应该可以做你想做的事情。