【python】字典和列表之间的爱恨缠绵的关系

python】字典和列表之间的爱恨缠绵的关系

说明

        此内容,简单粗暴,但是当自己的需求需要此种方式时,博主居然一脸蒙蔽不知云云,如何转换,故,以此记录,方便记忆!!!

一、方式一

1、源码

dictionary = {
    'ceshi1':'1',
    'ceshi2':'2',
    'ceshi3':'3',
}

for jian,zhi in dictionary.items():
    print('jian:',jian)
    print('zhi:',zhi)

2、结果

在这里插入图片描述

二、方式二

1、源码

dictionary = {
    'ceshi1':'1',
    'ceshi2':'2',
    'ceshi3':'3',
}



# 遍历字典列表
for jian,zhi in dictionary.items(): # items()以列表的形式返回可遍历的(键, 值) 元组数组
    print(jian + ' ' + zhi)
print('================================')

for jian,zhi in dictionary.items():
    print(jian,zhi)

2、结果
在这里插入图片描述

三、方式三

1、源码

dictionary = {
    'ceshi1':'1',
    'ceshi2':'2',
    'ceshi3':'3',
}


# 直接转换为列表
print("转换为列表 : %s" % list(dictionary.items()))
print("转换为列表:", list(dictionary.items()))

2、结果
在这里插入图片描述

四、方式四

遍历所有的键值

方式1

1、代码

dictionary = {
    'ceshi1':'1',
    'ceshi2':'2',
    'ceshi3':'3',
}

# 遍历字典中所以的键值
for jian in dictionary.keys():
    print(jian)

2、结果
在这里插入图片描述

方式2

1、源码

dictionary = {
    'ceshi1':'1',
    'ceshi2':'2',
    'ceshi3':'3',
}

# 遍历字典中所以的键值
# for jian in dictionary.keys():
#     print(jian)

for jian in  dictionary:
    print(jian)

2、结果
在这里插入图片描述

五、方式五

遍历字典所有的值

方式1

不考虑重复的值
1、源码

dictionary = {
    'ceshi1':'1',
    'ceshi2':'2',
    'ceshi3':'3',
}

for zhi in dictionary.values():
    print(zhi)

2、结果
在这里插入图片描述

方式2

考虑重复的值
1、源码

dictionary = {
    'ceshi1':'1',
    'ceshi2':'2',
    'ceshi3':'3',
    'ceshi4':'3',
}

for zhi in (set(dictionary.values())):
    print(zhi)

2、源码
在这里插入图片描述

发布了213 篇原创文章 · 获赞 303 · 访问量 49万+

猜你喜欢

转载自blog.csdn.net/Jiajikang_jjk/article/details/88367252