python编程--字典

字典

字典是一种动态结构,可随时在其中添加键—值对

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}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值