ZetCode

Python 创建字典

最后修改于 2024 年 1 月 29 日

Python 创建字典教程展示了如何在 Python 中创建字典。

在 Python 中有几种方法可以创建字典。 我们将在以下示例中演示它们。

Python 字典

Python字典是键值对的无序集合。 它是可变的,并且可以包含混合类型。 字典中的键必须是不可变的对象,例如字符串或数字。 它们在字典中也必须是唯一的。

Python 创建空字典

创建字典的一种方法是创建一个空字典,然后添加新的键值对。

empty.py
#!/usr/bin/python

capitals = {}

capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"

print(capitals)

该示例创建一个新的空字典,并添加新的键和值。

$ ./empty.py 
{'svk': 'Bratislava', 'dnk': 'Copenhagen', 'deu': 'Berlin'}

或者,我们可以使用 dict 函数创建一个新的空字典。

empty2.py
#!/usr/bin/python

capitals = dict()

capitals.update([('svk', 'Bratislava'), ('deu', 'Berlin'), ('dnk', 'Copenhagen')])

print(capitals)

使用 dict 创建一个空字典,并使用 update 添加新值

Python 使用字面量表示法创建字典

创建字典的常用方法是字面量表示法。 字典元素在 {} 括号内指定,并用逗号分隔。 键和值用冒号分隔。

literals.py
#!/usr/bin/python

cities = { 'Bratislava': 432000, 'Budapest': 1759000, 'Prague': 1280000, 
    Warsaw': 1748000, 'Los Angeles': 3971000, 'Edinburgh': 464000, 
    'Berlin': 3671000 }


print(cities['Bratislava'])
print(cities)

该示例使用字面量表示法创建一个城市字典。

Python dictionary fromkeys

fromkeys 是一个类方法,用于使用来自可迭代对象的键创建一个新字典,并将值设置为一个值。

fromkeys.py
data = ['coins', 'pens', 'books', 'cups'];

items = dict.fromkeys(data, 0)

print(items)

items['coins'] = 13
items['pens'] = 4
items['books'] = 39
items['cups'] = 7

print(items)

该示例从值列表创建一个新字典。 每个元素都初始化为零。 稍后,每个项目都被分配一个新的整数值。

$ ./from_keys.py 
{'coins': 0, 'pens': 0, 'books': 0, 'cups': 0}
{'coins': 13, 'pens': 4, 'books': 39, 'cups': 7}

元组列表创建字典

可以将元组列表传递给 dict 函数以创建一个新字典。

from_list_of_tuples.py
#!/usr/bin/python

data = [('Bratislava', 432000), ('Budapest', 1759000), ('Prague', 1280000), 
    ('Warsaw', 1748000), ('Los Angeles', 3971000), ('Edinburgh', 464000), 
    ('Berlin', 3671000)]

cities = dict(data)

print(cities['Bratislava'])
print(cities['Los Angeles'])
print(cities)

该示例创建一个带有嵌套元组的列表。 该列表被传递给 dict

将参数传递给 dict

创建字典的另一种方法是将参数传递给 dict 函数。

pass_params.py
#!/usr/bin/python

cities = dict(Bratislava = 432000, Budapest = 1759000, Prague = 1280000, 
    Warsaw = 1748000, Los_Angeles = 3971000, Edinburgh = 464000, Berlin = 3671000)

print(cities['Bratislava'])
print(cities)

这种方法有一个限制:洛杉矶必须用下划线连接。

使用 zip 与 dict

zip 函数接受可迭代对象(零个或多个),将它们聚合在一起,并返回一个基于可迭代对象的元组迭代器。

from_two_lists.py
#!/usr/bin/python

keys = ['coins', 'pens', 'books', 'cups'];
vals = [13, 4, 39, 7];

items = dict(zip(keys, vals))

print(items)

该示例使用 zip 连接两个列表,并将可迭代对象传递给 dict

Python 字典推导式

可以使用字典推导式从现有字典派生新字典。 字典推导式是一种语法结构,用于基于现有字典创建字典。

comprehension.py
#!/usr/bin/python

capitals = { "Bratislava": 424207, "Vilnius": 556723, "Lisbon": 564657,
             "Riga": 713016, "Jerusalem": 780200, "Warsaw": 1711324,
             "Budapest": 1729040, "Prague": 1241664, "Helsinki": 596661,
             "Yokyo": 13189000, "Madrid": 3233527 }


capitals2 = { key:val for key, val in capitals.items() if val < 1000000 }

print(capitals2)

在该示例中,我们从现有字典创建一个新字典。

capitals = { "Bratislava": 424207, "Vilnius": 556723, "Lisbon": 564657,
           "Riga": 713016, "Jerusalem": 780200, "Warsaw": 1711324,
           "Budapest": 1729040, "Prague": 1241664, "Helsinki": 596661,
           "Yokyo": 13189000, "Madrid": 3233527 }

我们有一个首都字典。 首都作为键,人口作为值。

capitals = { key:val for key, val in capitals.items() if val < 1000000 }

使用字典推导式创建一个新字典。 它包含人口少于一百万的首都。

$ ./comprehension.py
{'Bratislava': 424207, 'Vilnius': 556723, 'Jerusalem': 780200, 'Riga': 713016,
    'Lisbon': 564657, 'Helsinki': 596661}

这些首都的人口少于一百万。

来源

Python 数据结构 - 语言参考

在本文中,我们练习了在 Python 中创建字典。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程