Python implementation to add entries to the dictionary, python dictionary
This example describes how to add entries to a dictionary using python. It is a practical technique for dictionary operations. Share it with you for your reference.
The specific implementation method is as follows:
Def addWord (theIndex, word, pagenumber): theIndex. setdefault (word, []). append (pagenumber) # adds the list to the list if it exists. If it does not exist, a new dictionary key d = {"hello": [3]} # d = {} addWord (d, "hello", 3) addWord (d, "hello", 56) addWord (d, "nihao", 24) print d
The test environment in this article is Python2.7.6
The program running result is as follows:
{'nihao': [24], 'hello': [3, 3, 56]}
I hope this article will help you learn Python programming.
How to add the list elements to the dictionary in python?
A dictionary is a hash table with the value corresponding to the key.
For example, I want to initialize a dictionary.
Phonebook = {'Alice ': '000000', 'beth': '000000', 'ceil ': '000000 '}
In this way, the dictionary has three pairs of keys and corresponding values.
For example, here Alice, Beth, and Ceil are all keys.
The corresponding values are 3258, and respectively.
Keys and values are separated by colons (:), and items are separated by commas (,). The entire dictionary is enclosed by a pair of braces.
For example, if you want to query beth's phone number, you can use this statement:
Print phonebook ['beth ']
The result is 9274.
Are you familiar with the basic concepts of the dictionary ?!
Then, answer your question.
To add the elements in the list to the dictionary, you must provide the key value or value corresponding to {'A', 'B', 'C'} in d.
The first floor is one of the solutions, but some flaws should be:
A = dict (zip (d, [''] * 3 ))
The value of a is {'A': '', 'B':'', 'C ':''}
The values of Elements a, B, and c in the list are temporarily empty.
If you have any questions, please feel free to contact me! Wish you a pleasant programming!
How does the list () function of python convert the dictionary into a list?
Positive Solution. Unless you do not need dict, there is an OrderedDict in python that stores the insertion sequence.
Yes.
Z = collections. OrderedDict ()
Z ['banji '] = 'sanban ',
Z ['X'] = 'honging ',
Z ['nianji'] = 'wunianji'
Then you want the result.