Python-创建列表字典的方法
字典是无序,可更改和索引的集合。在Python中,字典用大括号括起来,并且具有键和值。您可以通过在方括号内引用其键名来访问词典的项目。
示例
# Creating an empty dictionarymyDict = {}
# Adding list as value
myDict["key1"] = [1, 2]
myDict["key2"] = ["Vishesh", "For", "Python"]
print(myDict)
# Creating an empty dictionary
myDict = {}
# Adding list as value
myDict["key1"] = [1, 2]
# creating a list
lst = ['vishesh', 'For', 'python']
# Adding this list as sublist in myDict
myDict["key1"].append(lst)
print(myDict)
# Creating an empty dict
myDict = dict()# Creating a list
valList = ['1', '2', '3']
# Iterating the elements in list
for val in valList:
for ele in range(int(val), int(val) + 2):
myDict.setdefault(ele, []).append(val)
print(myDict)
# Creating a dictionary of lists using list comprehension
d = dict((val, range(int(val), int(val) + 2))
for val in ['1', '2', '3'])
print(d)
输出结果
{'key2': ['Vishesh', 'For', 'Python'], 'key1': [1, 2]}{'key1': [1, 2, ['vishesh', 'For', 'python']]}
{1: ['1'], 2: ['1', '2'], 3: ['2', '3'], 4: ['3']}
{'1': [1, 2], '3': [3, 4], '2': [2, 3]}
以上是 Python-创建列表字典的方法 的全部内容, 来源链接: utcz.com/z/351441.html