python字典包含字典_庞大的Python字典指南

本文详细介绍了Python字典的特性和用法,包括如何创建和引用字典、字典的嵌套结构、遍历字典数据、字典在JSON中的应用以及性能考量。通过实例展示了字典在存储复杂数据时的优势,强调了字典在Python编程中的重要性及其高效性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python字典包含字典

什么是Python字典?

仅次于Python列表的字典或“ dict”是在内存中用于存储一系列值(也称为集合)的地方。 字典是特殊的,因为没有使用数字索引按顺序引用值。 而是在字典中, 用用户定义的键来引用值 ,就像物理词典中的单词是与其含义的“值”相关联的“键”一样。 该键通常是一个字符串,但可以是任意数量的数据类型。

<code class="Python hljs livecodeserver" style="box-sizing: border-box; font-size: 1.75 rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51 , 51 ); background: rgb(248, 248 , 248 ); border-radius: 0 px; line-height: 25 px; padding: 0.5 em 16 rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0 px; display: block; overflow-x: auto; border-top: 1 px solid rgb(224, 224 , 225 ); border-bottom: 1 px solid rgb(224, 224 , 225 );">my_dict = {<span class="hljs-string" style="box-sizing: border-box; color: rgb(221, 17 , 68 );">'my_key'</span> : <span class="hljs-string" style="box-sizing: border-box; color: rgb(221, 17 , 68 );">'my_value'</span>}</code>

例如,与其使用my_list [0]引用列表中的第一个值, 不如通过其键引用任何字典元素:

<code class="Python hljs livecodeserver" style="box-sizing: border-box; font-size: 1.75 rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51 , 51 ); background: rgb(248, 248 , 248 ); border-radius: 0 px; line-height: 25 px; padding: 0.5 em 16 rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0 px; display: block; overflow-x: auto; border-top: 1 px solid rgb(224, 224 , 225 ); border-bottom: 1 px solid rgb(224, 224 , 225 );"><span class="hljs-meta" style="box-sizing: border-box; color: rgb(153, 153 , 153 ); font-weight: 700 ;">&gt;&gt;&gt; </span>my_dict[<span class="hljs-string" style="box-sizing: border-box; color: rgb(221, 17 , 68 );">'my_key'</span>]
‘my_value’</code>

这些显式引用比列表索引符号更易读,并且在大多数情况下提高了代码的可维护性和性能。

此外,键值组合允许嵌套数据的复杂层次结构。 由于字典中的单词是其定义值的键,因此字母也可以是单词本身的值的键。 在处理复杂数据时,结构中数据的这种复杂性通常是必需的。 借助此特殊功能,词典可以位于列表和用户定义的类之间。 Python字典比列表具有更多的功能,但是不需要像具有唯一属性和方法的用户定义类那样费力。

如何创建和引用Python词典

根据情况,有几种声明字典的方法。 最简单的方法是将键和值括在花括号中,如下所示:

<codeclass = "Python hljs livecodeserver" style= "box-sizing: border-box; font-size: 1.75rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51, 51); background: rgb(248, 248, 248); border-radius: 0px; line-height: 25px; padding: 0.5em 16rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0px; display: block; overflow-x: auto; border-top: 1px solid rgb(224, 224, 225); border-bottom: 1px solid rgb(224, 224, 225);" >my_dict = {<span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'key1' </span>: <span class = "hljs-number" style= "box-sizing: border-box; color: teal;" > 1 </span>, <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'key2' </span>: <span class = "hljs-number" style= "box-sizing: border-box; color: teal;" > 2 </span>}</code>

您也可以将键值对传递给dict关键字构造函数,尽管这种情况不太常见:

<code class="Python hljs livecodeserver" style="box-sizing: border-box; font-size: 1.75 rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51 , 51 ); background: rgb(248, 248 , 248 ); border-radius: 0 px; line-height: 25 px; padding: 0.5 em 16 rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0 px; display: block; overflow-x: auto; border-top: 1 px solid rgb(224, 224 , 225 ); border-bottom: 1 px solid rgb(224, 224 , 225 );">my_dict = dict(key1 = <span class="hljs-number" style="box-sizing: border-box; color: teal;">1</span>, key2 = <span class="hljs-number" style="box-sizing: border-box; color: teal;">2</span>)</code>

当返回具有动态值的字典,或者作为lambda或理解的一部分时,在声明中分配值非常有用。 键和值都可以引用其他地方定义的变量,从而可以动态分配。

有时有必要声明一个空字典,因为稍后可能会添加值,但是与此同时,代码的其他部分也需要引用。

声明一个空字典:

<code class="Python hljs livecodeserver" style="box-sizing: border-box; font-size: 1.75 rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51 , 51 ); background: rgb(248, 248 , 248 ); border-radius: 0 px; line-height: 25 px; padding: 0.5 em 16 rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0 px; display: block; overflow-x: auto; border-top: 1 px solid rgb(224, 224 , 225 ); border-bottom: 1 px solid rgb(224, 224 , 225 );">my_dict = {}
my_dict = dict()</code>

值可以在赋值运算符可用时附加到此字典:

<codeclass = "Python hljs livecodeserver" style= "box-sizing: border-box; font-size: 1.75rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51, 51); background: rgb(248, 248, 248); border-radius: 0px; line-height: 25px; padding: 0.5em 16rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0px; display: block; overflow-x: auto; border-top: 1px solid rgb(224, 224, 225); border-bottom: 1px solid rgb(224, 224, 225);" >my_dict[<span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'key' </span>] = <span class = "hljs-number" style= "box-sizing: border-box; color: teal;" > 123 </span>

<span class = "hljs-meta" style= "box-sizing: border-box; color: rgb(153, 153, 153); font-weight: 700;" >&gt;&gt;&gt; </span>my_dict
{<span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'key' </span>: <span class = "hljs-number" style= "box-sizing: border-box; color: teal;" > 123 </span>}</code>

Python字典像其他任何变量一样被存储和引用。 实际上,字典可以存储在字典中,而且经常存储在字典中。 在这种情况下,只需像其他任何值一样,通过其键来引用存储的字典。

<codeclass = "Python hljs livecodeserver" style= "box-sizing: border-box; font-size: 1.75rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51, 51); background: rgb(248, 248, 248); border-radius: 0px; line-height: 25px; padding: 0.5em 16rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0px; display: block; overflow-x: auto; border-top: 1px solid rgb(224, 224, 225); border-bottom: 1px solid rgb(224, 224, 225);" >my_dict = {
    <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'my_nested_dict' </span>:
        {
            <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'a_key' </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'a_value' </span>,
            <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'another_key' </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'another_value' </span>,
        }
}</code>

有礼貌地使用空格,以清楚地指示嵌套的层,同时保持与Python最佳实践的一致性。 特定格式可以由IDE自动格式化程序或部署前的lint确定。

现在,我们可以通过其键引用嵌套字典:

<code class="Python hljs livecodeserver" style="box-sizing: border-box; font-size: 1.75 rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51 , 51 ); background: rgb(248, 248 , 248 ); border-radius: 0 px; line-height: 25 px; padding: 0.5 em 16 rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0 px; display: block; overflow-x: auto; border-top: 1 px solid rgb(224, 224 , 225 ); border-bottom: 1 px solid rgb(224, 224 , 225 );">my_variable = my_dict[<span class="hljs-string" style="box-sizing: border-box; color: rgb(221, 17 , 68 );">'my_nested_dict'</span>]</code>

字典理解–少即是多

定义字典的更高级技术是使用Python字典理解。 就像列表推导一样,字典推导会以比上述符号更简洁的格式生成动态大小的字典:

<code class="Python hljs livecodeserver" style="box-sizing: border-box; font-size: 1.75 rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51 , 51 ); background: rgb(248, 248 , 248 ); border-radius: 0 px; line-height: 25 px; padding: 0.5 em 16 rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0 px; display: block; overflow-x: auto; border-top: 1 px solid rgb(224, 224 , 225 ); border-bottom: 1 px solid rgb(224, 224 , 225 );">automatic_dictionary = {key: value <span class="hljs-keyword" style="box-sizing: border-box; color: rgb(51, 51 , 51 ); font-weight: 700 ;">for</span> (key, value) <span class="hljs-keyword" style="box-sizing: border-box; color: rgb(51, 51 , 51 ); font-weight: 700 ;">in</span> &lt; some_iterable &gt;}</code>

可以根据键和值(例如元组列表)进行关联的任何可迭代对象,都很容易成为具有一行代码的字典。 根据可迭代对象的大小,字典理解符号可以是一个节省空间的工具(和一个节省生命的工具!),使代码更加“ Pythonic”。

想要更快地编写代码吗?Kite是PyCharm,Atom,Vim,VSCode,Sublime Text和IntelliJ的插件,它使用机器学习为您提供按相关性实时排序的代码完成。 立即开始编码更快。免费下载Kite

实际用例

假设我们需要快速建立模型并存储一些数据,而无需创建类或冗长SQL语句。 例如,我们需要存储一些有关网站用户的数据。

用户类可能看起来像…

<codeclass = "Python hljs livecodeserver" style= "box-sizing: border-box; font-size: 1.75rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51, 51); background: rgb(248, 248, 248); border-radius: 0px; line-height: 25px; padding: 0.5em 16rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0px; display: block; overflow-x: auto; border-top: 1px solid rgb(224, 224, 225); border-bottom: 1px solid rgb(224, 224, 225);" ><span class = "hljs-class" style= "box-sizing: border-box;" ><span class = "hljs-keyword" style= "box-sizing: border-box; color: rgb(51, 51, 51); font-weight: 700;" > class </span> <span class = "hljs-title" style= "box-sizing: border-box; color: rgb(68, 85, 136); font-weight: 700;" >User</span><span class = "hljs-params" style= "box-sizing: border-box;" >( object )</span>:</span>
    <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > """  Stores info about Users """ </span>

    <span class = "hljs-function" style= "box-sizing: border-box;" ><span class = "hljs-keyword" style= "box-sizing: border-box; color: rgb(51, 51, 51); font-weight: 700;" >def</span> <span class = "hljs-title" style= "box-sizing: border-box; color: rgb(153, 0, 0); font-weight: 700;" > __ init __ </span><span class = "hljs-params" style= "box-sizing: border-box;" >(self, name, email, address, password, url)</span>:</span>
        self.name = name
        self.email = email
        ...

    <span class = "hljs-function" style= "box-sizing: border-box;" ><span class = "hljs-keyword" style= "box-sizing: border-box; color: rgb(51, 51, 51); font-weight: 700;" >def</span> <span class = "hljs-title" style= "box-sizing: border-box; color: rgb(153, 0, 0); font-weight: 700;" >send _ email</span><span class = "hljs-params" style= "box-sizing: border-box;" >(self)</span>:</span>
        <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > """ Send an email to our user""" </span>
        <span class = "hljs-keyword" style= "box-sizing: border-box; color: rgb(51, 51, 51); font-weight: 700;" >pass</span>

    <span class = "hljs-function" style= "box-sizing: border-box;" ><span class = "hljs-keyword" style= "box-sizing: border-box; color: rgb(51, 51, 51); font-weight: 700;" >def</span> <span class = "hljs-title" style= "box-sizing: border-box; color: rgb(153, 0, 0); font-weight: 700;" > __ repr __ </span><span class = "hljs-params" style= "box-sizing: border-box;" >()</span>:</span>
        <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > """Logic to properly format data""" </span>

bill = User(<span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'Bill' </span>, <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'bill @ gmail.com' </span>, <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > '123 Acme Dr.' </span>, <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'secret-password' </span>,
            <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'http: // www.bill.com' </span>)
bill.send _ email()</code>

这样的类可以具有各种功能,并且开发人员可以就是否使用新的@dataclass功能或我们是否需要类或实例方法等进行争论,但是有了字典,开销就更少了:

<codeclass = "Python hljs livecodeserver" style= "box-sizing: border-box; font-size: 1.75rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51, 51); background: rgb(248, 248, 248); border-radius: 0px; line-height: 25px; padding: 0.5em 16rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0px; display: block; overflow-x: auto; border-top: 1px solid rgb(224, 224, 225); border-bottom: 1px solid rgb(224, 224, 225);" >bill = {<span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'email' </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'bill@gmail.com' </span>,
    <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'address' </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > '123 Acme Dr.' </span>,
    <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'password' </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'secret-password' </span>,
    <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'url' </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'http://www.bill.com' </span>}

<span class = "hljs-function" style= "box-sizing: border-box;" ><span class = "hljs-keyword" style= "box-sizing: border-box; color: rgb(51, 51, 51); font-weight: 700;" >def</span> <span class = "hljs-title" style= "box-sizing: border-box; color: rgb(153, 0, 0); font-weight: 700;" >send_email</span><span class = "hljs-params" style= "box-sizing: border-box;" >(user_dict)</span>:</span>
    <span class = "hljs-keyword" style= "box-sizing: border-box; color: rgb(51, 51, 51); font-weight: 700;" >pass</span>
    <span class = "hljs-comment" style= "box-sizing: border-box; color: rgb(153, 153, 136); font-style: italic;" > # smtp email logic …</span>

send_email(bill[<span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'email' </span>])  <span class = "hljs-comment" style= "box-sizing: border-box; color: rgb(153, 153, 136); font-style: italic;" > # bracket notation or …</span>
send_email(bill. get (<span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > 'email' </span>))  <span class = "hljs-comment" style= "box-sizing: border-box; color: rgb(153, 153, 136); font-style: italic;" > # .get() method is handy, too</span></code>

现在我们可以像拥有Bill对象一样直观地拥有bill的数据,以及一半的代码。

遍历字典中存储的数据

由于JSON响应通常是字典列表(可能是从API响应中解析以生成User实例列表),因此我们可以遍历该字典以创建一些User实例。

<codeclass = "Python hljs livecodeserver" style= "box-sizing: border-box; font-size: 1.75rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51, 51); background: rgb(248, 248, 248); border-radius: 0px; line-height: 25px; padding: 0.5em 16rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0px; display: block; overflow-x: auto; border-top: 1px solid rgb(224, 224, 225); border-bottom: 1px solid rgb(224, 224, 225);" >json_response = [{
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "id" </span>: <span class = "hljs-number" style= "box-sizing: border-box; color: teal;" > 1 </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "first_name" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "Florentia" </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "last_name" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "Schelle" </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "email" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "fschelle0@nyu.edu" </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "url" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "https://wired.com" </span>
}, {
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "id" </span>: <span class = "hljs-number" style= "box-sizing: border-box; color: teal;" > 2 </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "first_name" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "Montague" </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "last_name" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "McAteer" </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "email" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "mmcateer1@zdnet.com" </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "url" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "https://domainmarket.com" </span>
}, {
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "id" </span>: <span class = "hljs-number" style= "box-sizing: border-box; color: teal;" > 3 </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "first_name" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "Dav" </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "last_name" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "Yurin" </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "email" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "dyurin2@e-recht24.de" </span>,
  <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "url" </span>: <span class = "hljs-string" style= "box-sizing: border-box; color: rgb(221, 17, 68);" > "http://wufoo.com" </span>
}]</code>

注意字典作为数据行的自然结构。 我们可以轻松地遍历这些行以创建我们的User对象。

<codeclass = "Python hljs livecodeserver" style= "box-sizing: border-box; font-size: 1.75rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51, 51); background: rgb(248, 248, 248); border-radius: 0px; line-height: 25px; padding: 0.5em 16rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0px; display: block; overflow-x: auto; border-top: 1px solid rgb(224, 224, 225); border-bottom: 1px solid rgb(224, 224, 225);" >users = []
<span class = "hljs-keyword" style= "box-sizing: border-box; color: rgb(51, 51, 51); font-weight: 700;" > for </span> i <span class = "hljs-keyword" style= "box-sizing: border-box; color: rgb(51, 51, 51); font-weight: 700;" > in </span> json_response:
    users.append(User(
        name=i [<span class="hljs-string" style="box-sizing: border-box; color: rgb(221, 17, 68);">'first_name'</span>] + i [<span class="hljs-string" style="box-sizing: border-box; color: rgb(221, 17, 68);">'last_name'</span>] ,
        email = i [<span class="hljs-string" style="box-sizing: border-box; color: rgb(221, 17, 68);">'email'</span>] ,
        url=i [<span class="hljs-string" style="box-sizing: border-box; color: rgb(221, 17, 68);">'url'</span>] ,
        <span class = "hljs-comment" style= "box-sizing: border-box; color: rgb(153, 153, 136); font-style: italic;" ># ...</span>
    ))</code>

字典作为嵌套数据结构

与列表相比,Python词典乍看起来似乎是死板而又不能原谅的:冒号和括号的名副其实的汤。 但是,与存储在关系数据库中的数据相比(字典中的值必须符合特定的约束条件才能使关系成为可能),字典非常灵活。

一方面,字典中的值可以是任何python对象,并且通常使用字典中的值实例化对象的集合。 值通过简单地“附加”便与其他值相关。 也就是说,将一个值放在列表或字典中,第一个值为键。 尽管以这种方式创建的字典可能看起来很复杂,但是将特定值从字典中拉出实际上比编写SQL查询要简单得多。

由于它们的结构,Python词典是理解其他嵌套数据结构(例如JSON或XML)的好方法-嵌套数据结构通常被称为非关系数据结构,除了关系数据库(如MySQL,PostgreSQL和其他数据库)外,它还包含所有内容。

刚度较小的结构的优点是可以轻松获取特定值。 缺点是,在其他键下的相应嵌套“级别”上的值集更难以彼此关联,并且生成的代码更冗长。 如果数据自然地落入列和行中,则更适合使用Pandas DataFrame或Numpy ndarray之类的东西,从而允许通过值在向量空间中的相对位置来引用值。

JSON的Python主页

尽管Python字典和JSON(JavaScript对象表示法)之间有一些细微的差异,但是这两种数据结构之间的相似性对于使用其他来源的数据的开发人员来说是一个很大的收获。 实际上,对请求库的响应调用.json()方法将返回一个字典。

最近,JSON已成为通过API进行数据交换的事实上的媒介,诸如XML和YAML的标记语言在很大程度上落后于后者。 导致这种情况的原因很可能是JavaScript的普及以及对Web服务能够将JavaScript与其他Web服务“说”的需求。 有些人认为,JSON的解压缩工作量很少。

幸运的是,或者也许是通过设计,Python很适合通过其本机数据结构(Python字典)使用JSON。 话虽这么说,这里有一些区别:

JSON用于序列化尽管Python开发人员习惯于操作内存中的Python对象,但JSON却是另一回事。 取而代之的是,JSON是一种标准,用于序列化各种数据以像通过HTTP的电报一样发送。 JSON通过网络传输后,就可以反序列化或加载到Python对象中。 JSON可以是一个字符串在JSON对象成为Python逻辑之前,它们通常是作为对HTTP请求的响应而发送的字符串,然后以各种方式进行解析。 JSON响应通常看起来像是用引号引起来的字典列表。 方便地,字典列表可以轻松地解析为更有用的对象,例如Pandas DataFrames(Pandas是Python的强大数据分析工具)。 每当加载和转储(序列化)JSON对象时,它们在某些时候都将成为Python中的字符串。 重复键 Python字典键必须唯一。 换句话说,some_dictionary.keys()将是一组唯一值。 JSON并非如此-这有点不寻常,因为它似乎一开始就破坏了密钥的用途-但从未有人说JSON是伪造的。 将JSON转换为Python对象时必须明确处理重复的键,否则只有一个键值对才能通过。想要更快地编写代码?Kite是PyCharm,Atom,Vim,VSCode,Sublime Text和IntelliJ的插件,使用机器学习为您实时提供按相关性排序的代码完成。 立即开始编码更快。免费下载Kite

陷阱和类似字典的选择

字典非常有用,但是语言规范的某些方面导致字典似乎行为不当。 例如,当遍历字典时,开发人员可以引用尚未定义的键值对。 Python字典不会返回“ None”,而是会引发错误并打印出回溯,如果未处理错误,则会完全停止执行。 此行为可能会减慢开发周期。

<code class="html hljs xml" style = "box-sizing: border-box; font-size: 1.75rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51, 51); background: rgb(248, 248, 248); border-radius: 0px; line-height: 25px; padding: 0.5em 16rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0px; display: block; overflow-x: auto; border-top: 1px solid rgb(224, 224, 225); border-bottom: 1px solid rgb(224, 224, 225);" >&gt;&gt;&gt; print (my_dict['my_key'])
Traceback (most recent call last ):
  File "<span class=" hljs-tag " style=" box -sizing: border - box ; color : navy; font -weight: 400 ; ">&lt;<span class=" hljs-name " style=" box -sizing: border - box ; color : navy; font -weight: 400 ; ">input</span>&gt;</span>" , line 1 , in <span class= "hljs-tag" style = "box-sizing: border-box; color: navy; font-weight: 400;" >&lt;<span class= "hljs-name" style = "box-sizing: border-box; color: navy; font-weight: 400;" >module</span>&gt;</span>
KeyError: 'my_key'</code>

由于程序通常可能只需要“检查”键值对的存在而不会引发错误,因此开发人员还有其他选择。 第一种是从collections模块导入defaultdict对象,这是一个自动覆盖的默认值自动覆盖的对象。 而不是显示错误,而是返回默认值。

其次,标准字典上的.get()方法可能返回作为第二个参数传递的任何值。 因此,引用一个值代替括号表示法,就像…

<codeclass = "Python hljs livecodeserver" style= "box-sizing: border-box; font-size: 1.75rem; font-family: &quot;Input Sans Narrow&quot;; color: rgb(51, 51, 51); background: rgb(248, 248, 248); border-radius: 0px; line-height: 25px; padding: 0.5em 16rem; white-space: pre; font-feature-settings: &quot;zero&quot;; letter-spacing: 0px; display: block; overflow-x: auto; border-top: 1px solid rgb(224, 224, 225); border-bottom: 1px solid rgb(224, 224, 225);" >just_checking = my_dict.get( < span class = "hljs-string" style = "box-sizing: border-box; color: rgb(221, 17, 68);" > 'my_key’, None) </ span > < span class = "hljs-string" style = "box-sizing: border-box; color: rgb(221, 17, 68);" >
&gt;&gt;&gt; print(just_checking) </ span > < span class = "hljs-string" style = "box-sizing: border-box; color: rgb(221, 17, 68);" >
None </ span > </ code >

好多了!

OrderedDict

字典被定义为键/值对的“无序”集合,这可能会带来不便。 为了添加有序行为,我们也有来自collections模块的OrderedDict 。 顾名思义,OrderedDict会按定义的返回顺序维护返回对。

尽管不如标准字典轻巧,但许多开发人员更喜欢使用OrderedDict,因为它的行为方式更可预测。 在标准字典中进行迭代时,键值对将以随机顺序返回。 OrderedDict始终以相同顺序返回对,这对于在大型数据集中查找特定对时很有用。 支持defaultdict和OrderedDict的人不要问“为什么?” –他们问:“为什么不呢?”

性能考量

您在Python应用程序中看到的性能不佳吗? 停止遍历列表,并开始引用字典中的值。

从技术上讲,可以使用列表来模仿字典的功能。 用列表创建键值对通常是一种编程入门。 但是,对于像Python这样的高级语言来说,拥有高性能的实现至关重要。 原因之一是Python语言实现本身在内部使用字典。

另一个原因是字典的执行速度比列表快。 在Python列表中,要找到特定项目,必须检查每个项目,直到找到匹配项。 对于字典,唯一选中的项目是与特定键相关联的项目(或对象或集合)。 这具有显着提高性能的效果,通常提高了几个数量级。

从这往哪儿走…

了解字典的最佳方法是进行练习! 尝试遍历字典,将键和值存储在单独的列表中,然后以适当的顺序将它们重新分配给彼此。

尝试根据字典创建有趣的对象系列,以及根据对象创建字典。 如果您必须在字典中存储1000行数据,那么解决该问题的一个很好的Python模式是什么?

在运行堆栈交换之前,请考虑一下字典的性质。 密钥是唯一值,还是可以重复? 如果它们是唯一的,哪种类型的Python集合可以最好地存储值? 现在,尝试搜索规范的解决方案。 当然,不要忘了查看字典中的官方Python文档:

https://docs.python.org/3/tutorial/datastructures.html

Python字典是Python中的基本数据结构,并且是Python语言规范的核心组件。 谨慎对待后,词典将成为高性能的工具,以一种明确,易读且最重要的是Python方式存储和访问复杂数据。

这篇文章是Kite关于Python的新系列的一部分。 您可以从我们的GitHub存储库中的这篇文章和其他文章中查看代码。

本文最初在风筝上发表。



翻译自: https://hackernoon.com/guide-to-python-dictionaries-gymx30aw

python字典包含字典

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值