04Python学习之路-字典

Python-字典

创建字典

如果学过OC 感觉, 一个样

>>> phonebook = {"Yuting":"123", "YKDog":"321", "Sudalv":"132"}

dict函数 转为字典
通过键找到值 d["age"]

>>> items = [("name", "YKDog"), ("age", 42)]
>>> d = dict[items]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'YKDog'}
>>> d["age"]
42

求长度

>>> phonebook = {"Yuting":"123", "YKDog":"321", "Sudalv":"132"}
>>> len(phonebook)
3

字典添加 清空

>>> d = {}
>>> d["name"] = "YKDog"
>>> d["age"] = 42
>>> d
{'name': 'YKDog', 'age': 42}
>>> returned_value = d.clear()
>>> returned_value
>>> 
>>> print(returned_value)
None

x = {}是产生一个新的空字典

>>> x = {}
>>> y = x
>>> x["key"] = "value"
>>> x
{'key': 'value'}
>>> y
{'key': 'value'}
>>> x = {}
>>> x
{}
>>> y
{'key': 'value'}

如果用clear 不用{}

>>> x = {}
>>> y = x
>>> x["key"] = "value"
>>> x
{'key': 'value'}
>>> y
{'key': 'value'}
>>> x.clear()
>>> x
{}
>>> y
{}

列表显示

>>> d = {"title":"Python Web Site", "url":"www.ykdog.com"}
>>> d.items()
dict_items([('url', 'www.ykdog.com'), ('title', 'Python Web Site')])

返回键列表

>>> d = {"title":"hehe", "content":"xixi"}
>>> d.keys()
dict_keys(['content', 'title'])

根据键删除键值对

>>> d = {"a":"A", "b":"B"}
>>> d.pop("a")
'A'
>>> d
{'b': 'B'}

删除首个item

>>> d = {"a":"A", "b":"B"}
>>> d.popitem()
('b', 'B')
>>> d
{'a': 'A'}

如果没有就加入, 如果有更新键值对。

>>> d = {"title":"Python", "url":"www.gou.com"}
>>> x = {"a":"A"}
>>> d.update(x)
>>> d
{'url': 'www.gou.com', 'a': 'A', 'title': 'Python'}
>>> x
{'a': 'A'}
>>> d.update({"a":"X"})
>>> d
{'url': 'www.gou.com', 'a': 'X', 'title': 'Python'}
>>> 

显示值

>>> d = {}
>>> d[1] = 1
>>> d[2] = 2
>>> d.values()
dict_values([1, 2])

一个很好的例子

== 用来表示值是否相等
is 用来判断是否为统一个对象

>>> x = [1, 2, 3]
>>> y = [2, 4]
>>> x is not y
True
>>> del x[2]
>>> x
[1, 2]
>>> y[1] = 1
>>> y
[2, 1]
>>> y.reverse()
>>> y
[1, 2]
>>> x == y
True
>>> x is y
False

输入

name = input("Your name:")
if 'dog' in name:
    print("wangwang")
else:
    print("GG")


>>> "alpha" < "beta"
True
>>> "go" > "tHH"
False

>>> [2, 1] > [1, 2]
True
x = 1
while x <= 100:
    print (x)
    x += 1
print("HeHe")


name = ''
while not name:
    name = input("Your name")
print ("Hello, %s" % name)

words = ["this", "is", "an", "ex", "parrot"]
for word in words:
    print(word)

d = {'x':1, 'y':2, 'z':3}
for key in d:
    print(key + " corresponds to " + str(d[key]))

结果
y corresponds to 2
x corresponds to 1
z corresponds to 3

你可能感兴趣的:(04Python学习之路-字典)