python中的字典是什么

393次阅读
没有评论

python中的字典是什么

字典定义

1.字典是存储信息的一种方式。

2.字典以键-值对存储信息,因此字典中的任何一条信息都与至少一条其他信息相连。

3.字典的存储是无序的,因此可能无法按照输入的顺序返回信息。

Python中定义字典

dictionary_name = {key_1: value_1, key_2: value_2}

为了更明显的显示数据,通常写成下面的格式:

dictionary_name = {key_1: value_1,
                   key_2: value_2
                   }

字典的基本用法

定义一个字典:

把 list、dictionary、function 的解释写成一个字典,请按下面的格式输出 dictionary 和 function 的定义

python_words = {'list': '相互没有关系,但具有顺序的值的集合',
                'dictionary': '一个键-值对的集合',
                'function': '在 Python 中定义一组操作的命名指令集',
                }
                
print("\n名称: %s" % 'list')
print("解释: %s" % python_words['list'])

字典的基本操作

逐个输出字典中的词条过于麻烦,因此可以使用循环输出

# name 和 meaning 可以随意该名称,试试改成 word 和 word_meaning
for name, meaning in python_words.items():
    print("\n名称: %s" % name)
    print("解释: %s" % meaning)

# 还有几种其他的输出方式,动手试一下。
print("***********************************************")
for word in python_words:
    print("%s" % word)
print("***********************************************")
for word in python_words.keys():
    print(word)
print("***********************************************")
for meaning in python_words.values():
     print("值: %s" % meaning)
print("***********************************************")
for word in sorted(python_words.keys()):
    print("%s: %s" % (word, python_words[word]))

给字典加入新的键-值对:

# 定义一个空字典
python_words = {}

# 给字典加入新项(词条):使用 字典名[键名] = 值 的形式可以给字典添加一个键-值对
python_words['Joker'] ='会玩 LOL'
python_words['Burning'] = '会玩 DOTA'
python_words['Elingsama'] = '会玩炉石传说'

def showMeanings(dictionary):
    for name, meaning in dictionary.items():
        print("\n名称: %s" % name)
        print("解释: %s" % meaning)

修改字典中的值:

# 使用 字典名[键名] = 新值 的形式更改已经存在的键-值对
python_words['Joker'] = 'LOL 的恶魔小丑'
print('\nJoker: ' + python_words['Joker'])

删除字典中的项:

# 返回 Joker 对应的值,同时删除 Joker 的键-值对
_ = python_words.pop('Joker')
# 删除 Buring 的键-值对
del python_words['Burning']
print(_)

修改键名:

# 1.创建一个新键
# 2.将要更换键名的值赋给新键
python_words['elingsama'] = python_words['Elingsama']
del python_words['Elingsama']

showMeanings(python_words
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-13发表,共计1944字。
新手QQ群:570568346,欢迎进群讨论 Python51学习