从[Awkward] Python嵌套字典中打印

vltsax25  于 2023-03-24  发布在  Python
关注(0)|答案(4)|浏览(138)

所以,我正在学习Python(3.x),这很有意义,直到我遇到了这个非常尴尬的字典进展,并试图更好地理解它在做什么。我希望有人能用[简单]的术语解释为什么它能工作/不能工作。
我完全意识到可能有更好的方法来做我正在努力做的事情-所以我也愿意看到和学习那些!
我需要在这些例子中提取/打印'this_entry'。

dict1 = {'simple':'this_entry'}
dict2 = {'key1':{'key2':'this_entry'}}
dict3 = {'key1':[{'nest_key':['this is harder',['this_entry']]}]}

前两个工作绝对罚款使用

print (dict1['simple'])
print (dict2['key1']['key2'])

但是第三个(显然是设计来的)要棘手得多,如果我使用

print (dict3['key1']['nest_key'][1])

它不工作并抛出错误...
所以为了调试,我从基本级别开始,看看什么工作/什么不工作。

print (dict3['key1'])                #shows [{'nest_key': ['this is harder', ['hello']]}]
print (dict3['key1']['nest_key'][1])    #breaks here showing: 
                                     #TypeError: list indices must be integers or slices, not str

如果我为键添加一个'pointer'(这是正确的词吗?)它有点工作,我只是想知道为什么它会中断,如果没有使用,为什么'pointer'在这个示例中需要(除了'没有它它就不能工作')。

print (dict3['key1'][0]['nest_key'][1])    #works-ish but shows entry ['hello'], not hello

我猜理解为什么我需要第一个[0]也会解释如何正确地提取我想要的条目?
先谢了!

pu3pd22g

pu3pd22g1#

对于给定的dict3 = {'key1':[{'nest_key':['this is harder',['this_entry']]}]},考虑运行以下语句,以及它们给出的输出:

>>> print(dict3["key1"]) # access the value of 'key1', the value is a list
[{'nest_key': ['this is harder', ['this_entry']]}]

>>> print(dict3["key1"][0]) # access the 1st elemtn of the list which is a dict
{'nest_key': ['this is harder', ['this_entry']]}

>>> print(dict3["key1"][0]["nest_key"]) # access the value of 'nest_key, the value is a list
['this is harder', ['this_entry']]

>>> print(dict3["key1"][0]["nest_key"][1]) # get 2nd element of the list, which is another list
['this_entry']

>>> print(dict3["key1"][0]["nest_key"][1][0]) # finaly get the single item in the list, value is a string
this_entry
n53p2ov0

n53p2ov02#

dict3['key1'] = [' nest_key':['this is harder',['hello']]}] #用数组中的字典回答
dict3['key1'][0] =' nest_key':['这更难',['hello']]} #仅使用字典进行回答(nest_key:2D阵列)
dict 3 ['key 1'][0]['nest_key']=['this is harder',['hello']] #用2D数组回答
dict 3 [“关键字1”][0][“嵌套关键字”][0] =“这更难”,[“您好”]
dict3['key1'][0]['nest_key'][0][1] = 'hello'

s4n0splo

s4n0splo3#

TL;DR

  • dict3['key1']-〉返回列表
  • [{'nest_key': ['this is harder']}]
  • dict3['key1'][0]-〉返回列表中的第一项
  • {'nest_key': ['this is harder']}
  • dict3['key1'][0]['nest_key']-〉返回内部dict中的nest_key值
  • ['this is harder']
  • dict3['key1'][0]['nest_key'][0]-〉返回内字典中的第一项
  • 'this is harder'
  • dict3['key1'][0]['nest_key'][1]-〉返回内字典中的第二项
  • ['this_entry']
  • dict3['key1'][0]['nest_key'][1][0]-〉返回内字典第二项中的第一个字符串
  • 'this_entry'
  • dict3['key1'][0]['nest_key'][1][0][0]-〉返回内字典第二项中第一个字符串的第一个字符
  • 't'

首先,collections.defaultdict是一个好朋友https://docs.python.org/3/library/collections.html#collections.defaultdict
示例用法:

from collections import defaultdict

x = defaultdict(list)
x['key1'].append('abc')

print(x)

[out]:

defaultdict(<class 'list'>, {'key1': ['abc']})

接下来,如果我们初始化dict3对象的“类型”,它看起来像这样:
在人类词汇中,字典列表字典列表字符串或字符串列表,即“凌乱”/“笨拙”,参见

在Python类型中:

from collections import defaultdict

x = defaultdict(lambda: [defaultdict] )

x['key1'].append({'abc': 'foo bar'})
print(x)

[out]:

defaultdict(<function <lambda> at 0x7f75cebca0d0>, 
{'key1': [<class 'collections.defaultdict'>, {'abc': 'foo bar'}]})

如果我们先看一下如何初始化dict3类型,你会这样做:

from collections import defaultdict

x = defaultdict(lambda: list(defaultdict(lambda: list)) )

x['key1'].append({'nest_key': ['this is harder']})
print(x)

[out]:

defaultdict(<function <lambda> at 0x7f75cee11940>, 
 {'key1': [defaultdict(<function <lambda>.<locals>.<lambda> at 0x7f75cf38c4c0>, {}), 
   {'nest_key': ['this is harder']}]})

然后要访问'this is harder'字符串,您可以执行以下操作:

  • x['key1']-〉返回列表
  • [{'nest_key': ['this is harder']}]
  • x['key1'][0]-〉返回列表中的第一项
  • {'nest_key': ['this is harder']}
  • x['key1'][0]['nest_key']-〉返回内部dict中的nest_key值
  • ['this is harder']
  • x['key1'][0]['nest_key'][0]-〉返回内字典中的第一项
  • 'this is harder'

但是如果我想要dict3 = {'key1':[{'nest_key':['this is harder',['this_entry']]}]}其中倒数第二个最里面的列表包含列表或字符串,会发生什么?
要初始化这些值,可以执行以下操作:

from collections import defaultdict

x = defaultdict(lambda: list(defaultdict(lambda: list)) )

x['key1'].append({'nest_key': ['this is harder']})

x['key1'][0]['nest_key'].append('this is inserting a string')
x['key1'][0]['nest_key'].append(['this is inserting a list'])

print(type(x['key1'][0]['nest_key'][0])) # "this is harder" -> str
print(type(x['key1'][0]['nest_key'][1])) # "this is inserting a string" -> str
print(type(x['key1'][0]['nest_key'][2])) # ['this is inserting a list'] -> list

[out]:

<class 'str'>
<class 'str'>
<class 'list'>

要总结初始化,请执行以下操作:
| 人话|初始化|用途|产出|
| - ------|- ------|- ------|- ------|
| 列表词典|x = defaultdict(list)|x['key1'].append('abc')|'key1':['abc']}|
| 法令目录词典|x = defaultdict(lambda:list(defaultdict)|x['key1'].append(' key2 ':'abc'})`|'key1':[|
| 列表字典|x = defaultdict(lambda:list(defaultdict(lambda:list)))|x [“密钥1”].append({“密钥2”:['foo bar']})|defaultdict(〈function at 0x7f75cebbcc10〉,'key1':[defaultdict(〈function .. at 0x7f75cebbc940〉,{}),'key2':['foo bar']}]})|

Q:如果我只是想访问对象内部的一个项,为什么要为如何初始化对象而烦恼呢?

答:如果你不知道对象是如何初始化的,你很可能无法修改/删除/添加项目。而且知道它是如何初始化的也有助于你理解如何访问里面的项目。

思考的食粮

如果访问/解析你想要的项目有点复杂,有没有更简单的方法来存储你的数据?也就是说,有没有更好的数据结构?

piok6c0g

piok6c0g4#

感谢所有的答案,我现在有一个更好的理解和理解的术语也更好.我认为这总结了我试图学习:

dict3 = {'key1':[{'nest_key':['this is harder',['this_entry']]}]}
# to extract/grab/print 'this_entry'
print (dict3['key1'][0]['nest_key'][1][0])

第一部分['key 1'][0]是必需的,因为它是一个只有一个元素的列表-这是我们/我想要访问的。接下来,查看['nest_key']索引1,因此[1],这里它又有一个元素,因此需要最终索引[0]。
这一切都更有意义,也更明白我错在哪里。

相关问题