Publicado en #TC101

Creation and use of dictionaries in Python

To begin it is important to know what is a dictionary, well a dictionary works similar to a list in which you can store information, but the dictionary will also organize it using this things called keys and not by order (there can’t be one key with to values, it would only save the last one). For example:

phonebook = {'Andrew Parson':8806336}
print(phonebook["Andrew Parson"])
...
8806336

Now that this is clear we need to know how to add or delete something, delete all, erase the dictionary, sort it, etc.

to delete an entry

del phonebook['Andrew Parson']

to add entries

phonebook['Sergio'] = 1234567

to change a value of an entry

phonebook['Sergio'] = 0

to erase all the entries

phonebook.clear()

to erase the hole dictionary

del phonebook

We also have build in functions to use with dictionaries, here I will write some:

len(dict)

this will give the number of items in the dictionary

str(dict)

this will transform the content in a string

dict.copy()

makes a copy from the dictionary

dict.get(key, default=None)

this will get the value assigned to a key

dict.has_key(key)

to check if a key exist, if it does return true.

dict.items()

to get tuples of all the entries in groups of key and value

dict.values()

returns a list of the values in the dictionary

sorry for the long post it has plenty information and for sure there is more so if you have more questions try this page: http://sthurlow.com/python/lesson06/

Deja un comentario