简单介绍字典
字典
字典是一种动态结构,可随时在其中添加键—值对
table = {'color': 'gray',
'price': 50,
}
new_price = table['price']
print("The table costs " + str(new_price) + " pounds!")
The table costs 50 pounds!
notice: str(new_price) can only concatenate str (not “int”) to str
增加属性
table['producer'] = 'Deli'
print(table)
{'color': 'Gray', 'price': 50, 'producer': 'Deli'}
改变删除键值
table['color'] = 'yellow'
del table['price']
print("The color of the table is " +table['color'].title() + ".")
遍历key和value:for key, value in table.items()
for key, value in table.items():
print("\nKey: " + key)
print("Value: " + str(value))
Key: color
Value: yellow
Key: producer
Value: Deli
遍历keys
for keys in table.keys():
print("Key: " + keys)
Key: color
Key: producer
for keys in sorted(table.keys()): 将keys按字母表排序
for language in set(favorite_languages.values()): 可以剔除重复值
# 创建一个用于存储桌子的空列表
tables= []
# 创建30个灰色的桌子
for table_number in range(30):
new_table = {'color': 'gray', 'price': 50, 'producer': 'Deli'}
tables.append(new_table)
一个键可以对应多个值
table = { ‘price’: 50, ‘material’: [‘wood’, ‘iron’], }
使用OrderedDict
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(name.title() + "'s language- " + language.title() + ".")
Jen's language- Python.
Sarah's language- C.
Edward's language- Ruby.
Phil's language- Python.
regular dictionary and ordered dictionary
d1 = {}
d1['a'] = 'A'
d1['b'] = 'B'
d1['1'] = '1'
d2 = {}
d2['1'] = '1'
d2['a'] = 'A'
d2['b'] = 'B'
print (d2 == d1)
-->True
d1 = collections.OrderedDict(d1)
d2 = collections.OrderedDict(d2)
print (d2 == d1)
-->False
在字典中存储字典
杂记
xx.title() 大写第一个字母
xx.upper() 大写全部字母
xx.lower() 小写全部字母
strip():删除字符串中的空白
lstrip/rstrip
python2:
3/2=1
In order to get the right value: 3.0/2 or 3/2.0 or 3.0/2.0
±*/
乘方:**
e.g. 3**2 = 9
列表,字典,元组,集合总结
list = [val1, val2, val3, val4]
dict = {key1: val1, key2, val2}
tuple = (val1, val2, val3, val4)
set = {val1, val2, val3, val4}