<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>映射 on 老张开工了</title>
    <link>/%E6%98%A0%E5%B0%84/</link>
    <description>Recent content in 映射 on 老张开工了</description>
    <generator>Hugo</generator>
    <language>zh-cn</language>
    <lastBuildDate>Wed, 06 May 2026 00:00:00 +0000</lastBuildDate>
    <atom:link href="/%E6%98%A0%E5%B0%84/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>字典与集合</title>
      <link>/posts/2026/05/dict-set/</link>
      <pubDate>Wed, 06 May 2026 00:00:00 +0000</pubDate>
      <guid>/posts/2026/05/dict-set/</guid>
      <description>上一篇文章我们学习了列表和元组这两种有序的序列类型。今天我们要学习的字典和集合则是以哈希表为基础的另一类数据结构，它们的特点是无序、高效，在实际编程中有着极其广泛的应用。&#xA;字典（Dict） 字典是一种键值对映射结构，通过键来快速查找对应的值。你可以把它想象成一本真正的字典——通过&amp;quot;词条&amp;quot;（键）来查找&amp;quot;释义&amp;quot;（值）。&#xA;创建字典 # 多种创建字典的方式 # 方式1：花括号 student = { &amp;#34;name&amp;#34;: &amp;#34;张三&amp;#34;, &amp;#34;age&amp;#34;: 20, &amp;#34;score&amp;#34;: 85 } print(student) # {&amp;#39;name&amp;#39;: &amp;#39;张三&amp;#39;, &amp;#39;age&amp;#39;: 20, &amp;#39;score&amp;#39;: 85} # 方式2：dict() 构造函数 person = dict(name=&amp;#34;李四&amp;#34;, age=25, city=&amp;#34;北京&amp;#34;) print(person) # {&amp;#39;name&amp;#39;: &amp;#39;李四&amp;#39;, &amp;#39;age&amp;#39;: 25, &amp;#39;city&amp;#39;: &amp;#39;北京&amp;#39;} # 方式3：由键值对列表创建 pairs = [(&amp;#34;name&amp;#34;, &amp;#34;王五&amp;#34;), (&amp;#34;age&amp;#34;, 30), (&amp;#34;city&amp;#34;, &amp;#34;上海&amp;#34;)] data = dict(pairs) print(data) # {&amp;#39;name&amp;#39;: &amp;#39;王五&amp;#39;, &amp;#39;age&amp;#39;: 30, &amp;#39;city&amp;#39;: &amp;#39;上海&amp;#39;} # 方式4：zip 创建 keys = [&amp;#34;name&amp;#34;, &amp;#34;age&amp;#34;, &amp;#34;city&amp;#34;] values = [&amp;#34;赵六&amp;#34;, 22, &amp;#34;广州&amp;#34;] info = dict(zip(keys, values)) print(info) # {&amp;#39;name&amp;#39;: &amp;#39;赵六&amp;#39;, &amp;#39;age&amp;#39;: 22, &amp;#39;city&amp;#39;: &amp;#39;广州&amp;#39;} # 方式5：字典推导式 squares = {x: x ** 2 for x in range(5)} print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} # 空字典 empty_dict = {} empty_dict2 = dict() 访问字典元素 student = {&amp;#34;name&amp;#34;: &amp;#34;张三&amp;#34;, &amp;#34;age&amp;#34;: 20, &amp;#34;score&amp;#34;: 85} # 使用方括号访问（键不存在会报错） print(student[&amp;#34;name&amp;#34;]) # 张三 print(student[&amp;#34;age&amp;#34;]) # 20 # print(student[&amp;#34;grade&amp;#34;]) # KeyError!</description>
    </item>
  </channel>
</rss>
