Python 练习实例100
题目:列表转换为字典。
程序分析:无。
程序源代码:
实例
#!/usr/bin/python# -*- coding: UTF-8 -*-i = ['a', 'b']l = [1, 2]printdict([i,l])
以上实例输出结果为:
{'a': 'b', 1: 2}
题目:列表转换为字典。
程序分析:无。
程序源代码:
以上实例输出结果为:
{'a': 'b', 1: 2}
灵犀
130***[email protected]
参考方法:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
l1=[1,2,3,6,87,3]
l2=['aa','bb','cc','dd','ee','ff']
d={}
for index in range(len(l1)):
d[l1[index]]=l2[index] # 注意,key 若重复,则新值覆盖旧值
print d
灵犀
130***[email protected]
红萝卜
101***[email protected]
参考方法:
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # 从列表创建字典 i = ['a','b','c'] l = [1,2,3] b=dict(zip(i,l)) print(b)
红萝卜
101***[email protected]
艾幻翔
cbi***@qq.com
参考方法:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
keys = ['a', 'b']
values = [1, 2]
print({keys[i]: values[i] for i in range(len(keys))})艾幻翔
cbi***@qq.com
kumbaya
zha***[email protected]
#!/usr/bin/python
# -*- coding: UTF-8 -*-
l1 = ['a','b','c']
l2 = [1,2,3]
d = {}
for i in range(len(l1)):
d.setdefault(l1[i],l2[i])
print dkumbaya
zha***[email protected]
mayi
law***[email protected]
使用 zip() 输出一个字母表的字典:
r = range(ord('a'), ord('z') + 1)
a = (i for i in r)
b = map(chr, r)
print(dict(zip(a, b)))
mayi
law***[email protected]