Basic python tutorials-A Dictionary of notes

Source: Internet
Author: User

Basic python tutorials-A Dictionary of notes

  • Create dictionary

A dictionary consists of multiple key-value pairs. Each key and corresponding value are separated by a colon, and items are separated by a comma. The entire dictionary is enclosed by a pair of braces, as shown in figure

>>> Phonebook = {'Alice ': '000000', 'betch': '000000', 'cecil': '000000 '}
>>> Phonebook
{'Betch': '000000', 'Alice ': '000000', 'cecil': '000000 '}

Dict-create a dictionary through a sequence pair or keyword such as other ing, (Key, value), such

>>> Items = [('name', 'gtum '), ('age', 42)]
>>> D = dict (items)
>>> D
{'Age': 42, 'name': 'gtum '}
>>> D ['age']
42
>>> D = dict (name = 'gtum ', age = 42)
>>> D
{'Age': 42, 'name': 'gtum '}

  • Basic operations

Len (d) -- returns the number of keys (key-value pairs) in d.

D [k] -- returns the value associated with the key k.

D [k] = v -- associate value v with key k

Del d [k] -- delete an item whose key is k

K in d -- check whether d contains k-key items.

The differences between dictionaries and lists are as follows:

Key type: the dictionary key can be any unchangeable type.

Auto-add: that is, the key does not exist in the dictionary at first, or you can assign a value to it.

>>> X = {}
>>> X [42] = 'F'
>>> X
{42: 'F '}

Membership: k in d searches for keys

# Simple database # use the name of a person as the key dictionary. Each person uses another dictionary to indicate their phone numbers and addresses, respectively. The keys 'phone' and 'add' indicate their phone numbers and addresses, people = {'Alice ': {'phone': '123 ', 'addr ': 'foo drive 23'}, 'bes': {'phone': '000000', 'addr': 'bar Street 42'}, 'cecil ': {'phone': '000000', 'add': 'baz avenue 90' }}# descriptive tags used for phone numbers and addresses, labels = {'phone': 'phone number', 'add': 'address'} name = raw_input ('name: ') will be used to print the output :') # Find the phone number or address? Use the correct key: request = raw_input ('key (p/a): ') # use the correct key: if request = 'P ': key = 'phone' if request = 'A': ker = 'add' # if the name is a valid key in the dictionary, the information is printed if name in people: print "% s's % s is % s. "% \ (name, labels [key], people [name] [key])

Result

Name: Beth
Key (p/a): p
Beth's phone number is 9102.

  • Dictionary Format String

Only use a string as the key dictionary to format the string, as shown in figure

>>> Phonebook = {'Alice ': '000000', 'betch': '000000', 'cecil': '000000 '}
>>> "Alice's phnoe is % (alice) s." % phonebook
"Alice's phnoe is 0123 ."

  • Dictionary Method

Clear -- clear all the items in the dictionary and directly apply to the original dictionary

Copy -- returns a salary point with the same key-value pair.

>>> X = {'username': 'admin', 'machines ': ['foo', 'bar']}
>>> Y = x. copy ()
>>> Y ['username'] = 'mlh'
>>> Y ['machines ']. remove ('foo ')
>>> Y
{'Username': 'mlh', 'machines ': ['bar']}
>>> X
{'Username': 'admin', 'machines ': ['bar']}

Deecopy -- deep copy

Fromkeys -- use the given key to create a new dictionary. The default value of each key is None, or you can provide the default value.

>>> X = dict. fromkeys (['name', 'age'], 'UN ')
>>> X
{'Age': 'non', 'name': 'non '}

Get -- access dictionary. If you access a key that does not exist, None is returned or the default value is customized.

>>> X. get ('it', 'n'/')
'N'/'

# Use the get () simple database people = {'Alice ': {'phone': '000000', 'addr ': 'foo drive 23'}, 'beth ': {'phone ': '123456', 'addr': 'bar Street 42'}, 'cecil ': {'phone': '123456', 'addr ': 'baz avenue 90' }}# use labels = {'phone': 'phone number' when printing and outputting descriptive labels for phone numbers and addresses ', 'addr ': 'address'} name = raw_input ('name:') # Find the phone number or address? Request = raw_input ('key (p/a): ') # use the correct key: key = request # if the request is neither 'P' nor 'A' if request = 'P': key = 'phone' if request = 'A ': key = 'add' # Use get () to provide the default value "person = people. get (name, {}) label = labels. get (key, key) result = person. get (key, 'not available') print "% s is % s. "% \ (name, label, result)

The result is as follows:

Name: Beth
Key (p/a):
Beth's address is Bar Street 42.

Has_key -- check whether the dictionary contains the given key

Items -- returns all dictionary items in the list. Each item in the list comes from (Key, value)

Iteritems -- Return iterator

Keys -- returns the keys in the dictionary as a list

Iterkeys -- return the iterator for the key

Pop -- obtain the value corresponding to the given key, and then remove the key-value pair from the dictionary.

Popitem -- a random item is displayed.

Setdefault -- get the value associated with the given key, and set the corresponding key value if the dictionary does not contain the given key

>>> X = {'username': 'admin', 'machines ': ['foo', 'bar']}
>>> X. pop ('username ')
'Admin'
>>> X = {'username': 'admin', 'machines ': ['foo', 'bar']}
>>> X. setdefault ('hh ', 'n'/')
'N'/'
>>> X
{'Username': 'admin', 'hh': 'n'/A', 'machines ': ['foo', 'bar']}
>>> X ['hh'] = 'hh'
>>> X. setdefault ('hh ', 'n'/')
'Hh'
>>> X
{'Username': 'admin', 'hh': 'hh', 'machines ': ['foo', 'bar']}

Update -- use one dictionary item to update another dictionary item. The provided dictionary items will be added to the old dictionary. If the same key exists, it will be overwritten.

>>> X = {'username': 'admin', 'machines ': ['foo', 'bar']}
>>> Y = {'hh ': 'hahaha '}
>>> X. update (y)
>>> X
{'Username': 'admin', 'hh': 'hahaha', 'machines ': ['foo', 'bar']}

Values -- returns the value in the dictionary in the form of a list. The list can contain duplicate elements.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.