I'm watching a python course and I saw a line of code that I don't understand
books_dict[title] = [author,subject,year]
what I see from this line is the key of books_dict
is the title and there are multiple values for it?
CodePudding user response:
You can print the type of books_dict[title]
with type()
function. It tells you that it's a list(so there is only one object). List is a container so it can contain other objects. In your dictionary there is only one value for that key. Whenever you access to that key you will get that one list not individual items inside it. That would be problematic then!
If you have:
d = {}
d["key1"] = [1, 2, 3]
CodePudding user response:
There is only one value, and that value is a list. The list is [author, subject, year]
.
CodePudding user response:
In addition to what others have already stated, a dictionary holds key, value pairs. One key to one value, however the data types used to create the key and value can both be containers holding more than one element
for example
books_dict[title] = [author,subject,year]
is the same as
temp = [author, subject, year]
books_dict[title] = temp
The key can also hold an iterable, however it must be hashable and immutable.
books_dict[(title, author)] = [subject, year]
which is the same as
key = (title, author)
value = [subject, year]
books_dict[key] = value