python 在线

956Python 字典(Dictionary)

Python 中的字典相当于 C++ 或者 Java 等高级编程语言中的容器 Map,每一项都是由 Key 和 Value 键值对构成的,当我们去访问时,根据关键字就能找到对应的值。

另外就是字典和列表、元组在构建上有所不同。列表是方括号 [],元组是圆括号 (),字典是花括号 {}

#coding:utf-8

users = {
    'A':{
    'first':'yu',
    'last':'lei',
    'location':'hs',
    },
    'B':{
    'first':'liu',
    'last':'wei',
    'location':'hs',    
    },
}
# username,userinfo 相当于 key,value
for username,userinfo in users.items():
    print("username:"+username)
    print("userinfo"+str(userinfo))
    fullname=userinfo['first']+" "+userinfo['last']
    print("fullname:"+fullname)
    print("location:"+userinfo['location'])

955Python 字典(Dictionary)

编写字典程序:

  • 1. 用户添加单词和定义
  • 2. 查找这些单词
  • 3.如果查不到,请让用户知道
  • 4. 循环
#coding:utf-8

# 字典创建  while开关 字典添加   字典寻找
dictionary = {}
flag = 'a'
pape = 'a'
off = 'a'
while flag == 'a' or 'c' :
    flag = raw_input("添加或查找单词 ?(a/c)")
    if flag == "a" :                             # 开启
        word = raw_input("输入单词(key):")
        defintion = raw_input("输入定义值(value):")
        dictionary[str(word)] = str(defintion)  # 添加字典
        print "添加成功!"
        pape = raw_input("您是否要查找字典?(a/0)")   #read
        if pape == 'a':
            print dictionary
        else :
            continue
    elif flag == 'c':
        check_word = raw_input("要查找的单词:")  # 检索
        for key in sorted(dictionary.keys()):            # yes
            if str(check_word) == key:
                print "该单词存在! " ,key, dictionary[key]
                break
            else:                                       # no
                off = 'b'
        if off == 'b':
            print "抱歉,该值不存在!"
    else:                               # 停止
        print "error type"
        break

测试输入:

添加或查找单词 ?(a/c)a
输入单词(key):facesoho
输入定义值(value):www.facesoho.com
添加成功!
您是否要查找字典?(a/0)0
添加或查找单词 ?(a/c)c 
要查找的单词:facesoho
该单词存在!  facesoho www.facesoho.com
添加或查找单词 ?(a/c)

954Python 字典(Dictionary)

字典值可以是任意数值类型:

>>> dict1 = {"a":[1,2]}      # 值为列表
>>> print dict1["a"][1]
2
>>> dict2 = {"a":{"c":"d"}}   # 值为字典
>>> print dict2["a"]["c"]
d
>>> 

953Python 元组

切片更新的不再是原来的元祖,而是生成了一个新的元祖副本:

>>> temp = (1, 2, 4, 5)
>>> id(temp)
43125640L
>>> temp = temp[:2] + (3,)
>>> id(temp)
43308160L

952Python 元组

关于元组的截取(补充 @Anofanog 的说明):

T = ('aa','bb','cc','dd','ee')

T[4] 得到的是字符串 'ee', 而 T[4:] 得到的是新元组 ('ee',),所以元组拼接时用 T[4] 会报错。

ps:T[4:4] 获取的值为空。