The next day insist!!!!
1. How to implement a dictionary (also called multidict) in which keys correspond to multiple values?
If a key maps multiple values, multiple values need to be placed in a container, such as a list or collection.
data = { 'a':[1,2,3], 'b':[4,5] } data_set = { 'a':{1,2,3}, 'b':{4,5}, } # Whether we use lists or collections depends on ourselves. # If you want to keep the insertion order of elements, you should use lists, and if you want to get rid of duplicate elements, you should use collections!!!!! # Use defaultdict in collections module to construct such a dictionary from collections import defaultdict data = defaultdict(list) data['a'].append(1) data['a'].append(2) data['b'].append(3) print(data.items()) # dict_items([('a', [1, 2]), ('b', [3])]) data = defaultdict(set) data['a'].add(1) data['a'].add(1) data['b'].add(4) data['b'].add(3) data['a'].add(5) print(data.items()) # dict_items([('a', {1, 2}), ('b', {4})])
2. How to find the minimum, maximum and sort the dictionary?
# Create a dictionary prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } # Find the minimum and maximum keys and values min_price = min(zip(prices.values(), prices.keys())) print(min_price) # (10.75, 'FB') max_price = max(zip(prices.values(), prices.keys())) print(max_price) # (612.78, 'AAPL') # Use zip() and sorted() functions to arrange dictionary data price_sorted = sorted(zip(prices.values(),prices.keys())) print(price_sorted) # [(10.75, 'FB'), (37.2, 'HPQ'), (45.23, 'ACME'), (205.55, 'IBM'), (612.78, 'AAPL')] prices_and_names = zip(prices.values(), prices.keys()) print(min(prices_and_names)) # (10.75, 'FB') # The zip() function creates an iterator that can only be accessed once # print(max(prices_and_names)) # ValueError: max() arg is an empty sequence print(min(prices, key=lambda k:prices[k])) # Output Minimum Valuable Key FB # If you want to get the key, you need to perform a lookup operation print(prices[min(prices, key=lambda k:prices[k])]) # 10.75 '''It is used in computing operations. (Key, value) Yes. When multiple entities have the same value, //The key determines the return result. For example, when performing min() and max() operations, if it happens to be minimal or //If the maximum value is repeated, the entity with the smallest or largest key will return'''' prices = { 'ccc' : 45.23, 'AAA': 45.23 } print(min(zip(prices.values(),prices.keys()))) # (45.23, 'AAA') print(max(zip(prices.values(),prices.keys()))) # (45.23, 'ccc')
3. Find the same point (same key, same value) between two dictionaries.
a = { 'x': 1, 'y': 2, 'z': 3, } b = { 'w': 10, 'x': 11, 'y': 2, } print( a.keys() & b.keys() ) # Get the same key {y','x'} print( a.keys() - b.keys() ) # Get the key {'z'} that b does not have in a print( a.items() - b.items() ) # Get the same key, value {'z'} in a and B #Construct a new dictionary that excludes several specified keys from the existing dictionary. print({key:a[key] for key in a.keys() - {'z','w'}})
Discussions:
A dictionary is a mapping relationship between a set of keys and a set of values. The keys() method of the dictionary returns a key view object that represents a collection of keys. A little-understood feature of key views is that they also support set operations, such as set union, intersection, and subtraction. So, if you want to perform some common set operations on the keys of a collection, you can use the key view objects directly instead of converting them into a set first. The items() method of the dictionary returns an element view object containing (key, value) pairs. This object also supports set operations and can be used to find which key-value pairs are the same in both dictionaries. Although the values() method of the dictionary is similar, it does not support the set operations described here. To some extent, the value view does not guarantee that all values are different from each other, which can lead to problems in some set operations. However, if you insist on performing these set operations on values, you can first convert the set of values into a set, and then perform the set operation. From the book Python Cookbook, you can leave a message if you need information.
4. How to eliminate duplicate values while maintaining element order on a sequence?
# Solving this problem with sets or generators def dedupe(items,key=None): seen = set() for item in items: val = item if key is None else key(item) if val not in seen: print(val) yield item seen.add(val) a = [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}] print(list(dedupe(a, key=lambda d: (d['x'],d['y'])))) # [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}] print(list(dedupe(a, key=lambda d: (d['x'])))) # [{'x': 1, 'y': 2}, {'x': 2, 'y': 4}] # The same list can be solved by collections or generators! def dedupe(items): seen = set() for item in items: if item not in seen: yield item seen.add(item) a = [1, 5, 2, 1, 9, 1, 5, 10] print(list(dedupe(a))) # List must take oh no list to generate an object print(set(a)) # If you only want to remove duplication, you can use set() ''' //Reading a file to eliminate duplicate rows can also be done in this way ''' with open(file,'r') as f: for line in dedupe(f): print(line)