Python (data structure and algorithm [3])

Source: Internet
Author: User

Python (data structure and algorithm [3])

Maps keys to multiple values in the dictionary.

One-click multi-value dictionary

d = {'a':[1,2,3], 'b':[4,5]}e = {'a':{1,2,3}, 'b':{4,5}}

You can use the from collections import defaultdict to use the default dictionary class. One feature of the default dictionary class is to automatically initialize the first value. You only need to pay attention to adding elements later.

from collections import defaultdictd = defaultdict(list)d['a'].append(1)d['a'].append(4)...d = defaultdict(set)d['a'].add(5)...

Example:

d = defaultdict(list)for key, value in pairs: d[key].append(value)
Keep the dictionary in order
from collections import OrderedDictd = OrderedDict()d['grok'] = 4d['foo'] = 1d['abr'] = 2for key in d: print(key, d[key])

Output:

grok 4foo 1abr 2

When the dictionary is iterated, it will strictly follow the initial addition order of the elements.

Dictionary-related computing problems
Prices = {'acme ': 45.23, 'aap': 612.78, 'ibm': 205.55, 'hpq': 37.20, 'fb ': 10.75} # Use zip () reverse the dictionary key and value to min_price = min (zip (prices. values (), prices. keys () max_price = max (zip (prices. values (), prices. keys () print (min_price) print (max_price) # To sort data, you only need to use the sorted function price_sorted = sorted (zip (prices. values (), prices. keys () for key, value in price_sorted: print (key, value)

Output:

(10.75, 'FB')(612.78, 'AAPL')10.75 FB37.2 HPQ45.23 ACME205.55 IBM612.78 AAPL

Let's take a look at the effect if zip () is not used?

Prices = {'acme ': 45.23, 'aap': 612.78, 'ibm': 205.55, 'hpq': 37.20, 'fb ': 10.75} print (min (prices )) # Only the print (min (prices. values () # Only search for values. values cannot be mapped to keys. // Add prices = {'aaa': 34, 'bbb ': 34} print (min (zip (prices. values (), prices. keys () # Compare the value size when the value is equal after the reversal
Search for similarities between the two dictionaries
a = { 'x' : 1, 'y' : 2, 'z' : 3}b = { 'w' : 10, 'x' : 11, 'y' : 2}print('Common keys:', a.keys() & b.keys())print('Keys in a not in b:', a.keys() - b.keys())print('(key,value) pairs in common:', a.items() & b.items()

Output:

Common keys: {'y', 'x'}Keys in a not in b: {'z'}(key,value) pairs in common: {('y', 2)}

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.