【python】 dictionary

一些字典的基本操作
.items()
.keys()
.values()
.get(self, key, dafault)
sorted() 该对字典进行排序的时候,返回的是列表

import operator

#字典
#使用花括号定义  a = {...}
#key-value  (value可以是任意数据类型)
def base_operate():
    alien = {'color': 'yellow', 'points': 5}
    print(alien['color'])
    print(alien['points'])
    #print(alien['3'])  #报错  KeyError: '3'
    #print(alien[0])  #不可以使用下标访问

    #添加key-value
    alien['head'] = "so big"
    print(alien['head'])

    #删除字典中的元素
    del(alien['points'])
    print(alien)

    #遍历字典
    # 字典不关心键—值对的存储顺序, 而只跟踪键和值之间的关联关系
    print(alien.items())  # 返回一个 键—值对 列表
    for key, value in alien.items():
        print(key + ": " + value)

    print(alien.keys()) # 返回一个 键 列表
    for key in alien.keys():
        print(key)
    print(len(alien.keys()))  # 2

    # not in
    # if "hand" not in alien.keys():
    #     alien["hand"] = 2
    # print(alien["hand"]) # 2

    alien["hand"] = 3
    #.get(self, key, default)
    alien["hand"] = alien.get("hand", 2)
    print(alien["hand"]) # 如果没有alien["hand"] = 3这一句, 那么输出2, 否则输出3

    #按 key 顺序遍历字典
    favorite_languages = {
        'jen': 'python',
        'sarah': 'c',
        'edward': 'ruby',
        'phil': 'python',
    }
    for name in sorted(favorite_languages.keys()):
        print(name.title() + ", thank you for taking the poll.")

    #遍历 value
    for value in favorite_languages.values():
        print(value)

    #对字典进行排序  !!!!!!!
    nation = {"china": 200, 'usa': 300, "japan": 100}
    #  key为函数,指定取待排序元素的哪一项进行排序
    # operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号)
    sortedNation = sorted(nation.items(), key = operator.itemgetter(1))
    print(type(sortedNation))  # 
    print(sortedNation)    # key = operator.itemgetter(1) 时 [('japan', 100), ('china', 200), ('usa', 300)]
    #print(sortedNation)    # key = operator.itemgetter(0) 时 [('china', 200), ('japan', 100), ('usa', 300)]
    print(sortedNation[0][0])  # china


def main():
    base_operate()


if __name__ == "__main__":
    main()

你可能感兴趣的:(python)