Python – 将值添加到列表字典
在本文中,我们将讨论如何将值添加到列表字典中。
我们可以使用列表向字典添加值,输入列表将是以下结构:
[('key',value),...........,('key',value)]
所以上面的列表是一个输入,我们可以使用 for 循环将值添加到列表字典中。
Syntax:
for key, value in input:
data[key].append(value)
where,
- key is the key in the input list
- value is the value in the input list
示例 1:创建学生科目输入列表并添加到列表字典的Python程序
Python3
# import defaultdict module
from collections import defaultdict
# declare a list with student data
input = [('bhanu', 'html'),
('bhanu', 'php'),
('suma', 'python'),
('rasmi', 'java'),
('suma', 'html/csscss')]
# declare a default dict
data = defaultdict(list)
# append to the dictionary
for key, value in input:
data[key].append(value)
# display
print(data.items())
Python3
# import defaultdict module
from collections import defaultdict
# declare a list with student data with age
input = [('bhanu', 10), ('uma', 12), ('suma', 11)]
# declare a default dict
data = defaultdict(list)
# append to the dictionary
for key, value in input:
data[key].append(value)
# display
print(data.items())
输出:
dict_items([(‘bhanu’, [‘html’, ‘php’]), (‘suma’, [‘python’, ‘html/csscss’]), (‘rasmi’, [‘java’])])
示例 2:
Python3
# import defaultdict module
from collections import defaultdict
# declare a list with student data with age
input = [('bhanu', 10), ('uma', 12), ('suma', 11)]
# declare a default dict
data = defaultdict(list)
# append to the dictionary
for key, value in input:
data[key].append(value)
# display
print(data.items())
输出:
dict_items([('bhanu', [10]), ('uma', [12]), ('suma', [11])])