第七章 字典和集合[DDT书本学习 小甲鱼]【1】

7.1 字典 当索引不好用时
a1=["我","你","她"]
a2=["我很好","你很好","她很好"]
print("我要说的是:",a2[a1.index("我")])

7.1.1 创建和访问字典
变成字典形式:
dict1={"我":"我很好","你":"你很好","她":"她很好"}
print(dict1["你"])
--------------------
你很好
===================================
映射关系 字典{} 组成部分由(键:值)
序列类型 列表[] 元组() 字符串""
====================
dict2={1:"one",2:"two",3:"three"}
print(dict2[2])
-------------------
two
=====================
dict3={}
print(dict3)
----------
{}
========================
dict4=dict((("F",70),("i",105),("s",115),("h",104),("c",67)))
print(dict4)
----------------------
{'F': 70, 'i': 105, 's': 115, 'h': 104, 'c': 67}
====================================================
dict5=dict(我="世界",你="房子",她="火车") #加引号会报错
print(dict5)
---------------------------
{'我': '世界', '你': '房子', '她': '火车'}
======================================================
给键改值,如果没有该键,【创建】该键和值。
代码如下
dict5=dict(我="世界",你="房子",她="火车") #加引号会报错
dict5["你"]="坦克"
dict5["他们"]="狼群"
print(dict5)
-----------------------------------------
{'我': '世界', '你': '坦克', '她': '火车', '他们': '狼群'}
===========================================================
总结下面5种方法,都可以用来创建字典,仔细体会:
a=dict(one=1,two=2,three=3)
b={"one":1,"two":2,"three":3}
c=dict(zip(["one","two","three"],[1,2,3]))
d=dict([("two",2),("one",1),("three",3)])
e=dict({"one":1,"two":2,"three":3})
print(a)
print(b)
print(c)
print(d)
print(e)
---------------------------------------------
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'two': 2, 'one': 1, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}

猜你喜欢

转载自www.cnblogs.com/daodantou/p/10328321.html
今日推荐