python dictionary using a multi-value key / key judgment of the dictionary is located

A dictionary associated with a container, each key is mapped to a single value. If you want the key is mapped to a plurality of values, you can save the plurality of values ​​to another vessel (collection or list) of.

You can do

Create dictionary

d={
‘a’:[1,2,3],
'b':[4,5]
"c":8
}

#或者这样创建:

d={
'a':{1,2,3},
'b':{4,5}
"c":8
}

To create a list or a collection depends entirely on the application of intent. If you want to retain the order of the elements inserted, use the list, if you want to eliminate duplicate elements (and do not care about their sort), to use the collection.

In order to facilitate the creation of such a dictionary may be utilized defaultdict class collections module. Defaultdict a feature is that it automatically initializes the first value, so you can just focus on adding elements:

from collections import defaultdict

d=defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)

print(d)

d=defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)

print (d)
Results:

defaultdict(<class 'list'>, {'a': [1, 2], 'b': [4]})
defaultdict(<class 'set'>, {'a': {1, 2}, 'b': {4}})

Common key values ​​corresponding to the dictionary str or int type, but a multi-key corresponding to the value of the type of list, judges whether a list type when the isinstance () function

To determine whether the list:

print(isinstance(slink,list))

The results: true explanation for the list (list)
false description does not list (list)

Examples

The following example demonstrates the use of isinstance function:

a = 2

 isinstance (a,int)

>>>True

 isinstance (a,str)

>>>False

Use a key multi-value dictionary

To create

d={
‘a’:[1,2,3],
'b':[4,5]
"c":8
}

Can used[‘a'][0] d[‘a'][1] d[‘a'][2]

print(`d[‘a'][0])
print(`d[‘a'][1])
print(`d[‘a'][2])

The results were 2, 3

Determining whether a key located in the dictionary

d={
‘a’:[1,2,3],
'b':[4,5]
"c":8
}
print("a" in d)
print("e" in d)
>>>True
>>>False
Published 12 original articles · won praise 0 · Views 216

Guess you like

Origin blog.csdn.net/Alden_Wei/article/details/104421322