![]() |
|
[Tut] Python dict() — A Simple Guide with Video - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python dict() — A Simple Guide with Video (/thread-99024.html) |
[Tut] Python dict() — A Simple Guide with Video - xSicKxBot - 03-20-2022 Python dict() — A Simple Guide with Video Python’s built-in Code: dict()Code: key = valueCode: dict(name = 'Alice', age = 22, profession = 'programmer')Code: {'name': 'Alice', 'age': 22, 'profession': 'programmer'}Read more about dictionaries in our full tutorial about Python Dictionaries. ![]() Usage Learn by example! Here are some examples of how to use the Code: dict()Code: >>> dict(name = 'Alice')
{'name': 'Alice'}
>>> dict(name = 'Alice', age = 22)
{'name': 'Alice', 'age': 22}
>>> dict(name = 'Alice', age = 22, profession = 'programmer')
{'name': 'Alice', 'age': 22, 'profession': 'programmer'}You can pass an arbitrary number of those comma-separated Code: key = valueCode: dict()Video dict() Syntax dict() You can use the Code: dict()Code: key=valueCode: Syntax: There are four ways of using the constructor:
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs
dict(iterable) -> new dictionary initialized from an iterable of (key, value) tuples
dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list.Interactive Shell Exercise: Understanding dict() Consider the following interactive code: https://trinket.io/embed/python/3b90f6252a Exercise: Guess the output before running the code. But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link). If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python! ![]() The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). Link: https://nostarch.com/pythononeliners The Code: dict()Code: dict()How to Create an Empty Dictionary? You can create an empty dictionary by using Python’s built-in Code: dict()Code: d[key] = valueCode: >>> d = dict()
>>> d['Alice'] = 22
>>> d
{'Alice': 22}You can create a dictionary with initial Code: key: valueCode: dict(name = 'Alice', age = 22)Code: {'name': 'Alice', 'age': 22}Code: >>> dict(name = 'Alice', age = 22)
{'name': 'Alice', 'age': 22}You can initialize your new dictionary by using an iterable as an input for the Code: dict(iterable)Code: (key, value)Code: >>> dict([(1, 'one'), (2, 'two')])
{1: 'one', 2: 'two'}
>>> dict([[1, 'one'], [2, 'two']])
{1: 'one', 2: 'two'}
>>> dict(((1, 'one'), (2, 'two')))
{1: 'one', 2: 'two'}Note that you can use inner tuples, inner lists, outer tuples or outer lists—as long as each inner collection contains exactly two values. If it contains more, Python raises an Code: ValueError: dictionary update sequence elementCode: >>> dict([(1, 'one', 1.0), (2, 'two', 2.0)])
Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> dict([(1, 'one', 1.0), (2, 'two', 2.0)])
ValueError: dictionary update sequence element #0 has length 3; 2 is requiredYou can fix this Code: ValueErrorHow to Create a Dictionary Using an Existing Mapping Object? If you already have a mapping object such as a dictionary mapping keys to values, you can pass this object as an argument into the Code: dict()Code: key: valueCode: >>> d = {'Alice': 22, 'Bob': 23, 'Carl': 55}
>>> d2 = dict(d)
>>> d
{'Alice': 22, 'Bob': 23, 'Carl': 55}If you now change the original dictionary, the change is not reflected in the new dictionary Code: d2Code: >>> d['David'] = 66
>>> d
{'Alice': 22, 'Bob': 23, 'Carl': 55, 'David': 66}
>>> d2
{'Alice': 22, 'Bob': 23, 'Carl': 55}Interestingly, you can also pass a mapping object into the Code: dict()Code: key: valueCode: dict({'Alice': 22}, Bob = 23)Code: key:valueCode: {'Alice': 22, 'Bob': 23}Code: >>> dict({'Alice': 22}, Bob = 23)
{'Alice': 22, 'Bob': 23}
>>> dict({'Alice': 22}, Bob = 23, Carl = 55)
{'Alice': 22, 'Bob': 23, 'Carl': 55}Similarly, you can also pass an iterable of (key, value) tuples into the Code: dict()Code: key: valueCode: dict([('Alice', 22)], Bob = 23)Code: key:valueCode: {'Alice': 22, 'Bob': 23}Code: >>> dict([('Alice', 22)], Bob = 23)
{'Alice': 22, 'Bob': 23}
>>> dict([('Alice', 22), ('Carl', 55)], Bob = 23)
{'Alice': 22, 'Carl': 55, 'Bob': 23}Python’s built-in Code: dict()Code: key = valueFor example, Code: dict(name = 'Alice', age = 22, profession = 'programmer')Code: {'name': 'Alice', 'age': 22, 'profession': 'programmer'}Code: >>> dict(name = 'Alice', age = 22, profession = 'programmer')
{'name': 'Alice', 'age': 22, 'profession': 'programmer'}A dictionary is an unordered and mutable data structure, so it can be changed after creation. I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy: Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder! Where to Go From Here? Enough theory, let’s get some practice! To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! The post Python dict() — A Simple Guide with Video first appeared on Finxter. |