wlbk.net
当前位置:首页 >> python中字典的输出 >>

python中字典的输出

#coding:utf-8dic = {'张三':2,'李四':3,'王五':5}line = None for key in dic: if line != None:line += "," else: line = "{" line += "'" + key + "':" + str(dic[key])line += "}"print line

python字典同一个键只能有一个value值,再次赋值会顶掉之前的value值,如果想一个键里面存多个值可以将键对应的value值设置成list类型,不断向list追加元素就可以了

1234567891011 #coding:utf-8dic ={'张三':2,'李四':3,'王五':5}line =Noneforkey indic: ifline !=None: line +="," else: line ="{" line +="'"+key +"':"+str(dic[key])line +="}"printline

dic={"233":"233",233:"666"} print dic["233"] print dic[233]也就是说,对于一个字典dic,dic[键值]就是该键值所对应的值

最为简单的方法是利用表理解,生成一个新的字典 必须要保证键值是一一对应的 d = {'one':1, 'two':2, 'three':3, 'four':4} di = {v:k for k,v in d.items()} di[1]

参考代码#!/usr/bin/env python# -*- coding: utf-8 -*-#python 2.7import urllibdef xz(name,link): #通过链接读取到数据 sj = urllib.urlopen(link).read() #写入二进制数据到文件里 with open("d:\\"+name,"wb") as fo: fo.write(sj)#字典dt = {"tp1.jpg":"..链接1tp1.jpg","tp2.jpg":"..链接2..tp2.jpg"}for name,link in dt.items(): xz(name,link)print '--ok--'

a = str(raw_input(u"请输入用空格分开的单词:"))b = a.split()b.sort()for i in b: print i

你是希望按照输入顺序输出还是按照key或者value的排序输出呢?如果按照输入顺序输可以这样(方法一):# 通过zip方法合并两个List为Dictionary# 遍历会按原先的顺序 keys = ["b", "a", "c", "e", "d"] values = ["2", "1", "3",

dict是哈希实现的,不存在有序无序想要实验有序输出,按list就行ATLst = sorted(ATDict.items(),key=lambda x:x[0],reverse=True)for item in ATLst:print(items[0],items[1])

#coding:utf-8dict={'a':"你好","世界":'b'}print dict['a']print dict["世界"]

qwrx.net | realmemall.net | zxwg.net | rxcr.net | tbyh.net | 网站首页 | 网站地图
All rights reserved Powered by www.wlbk.net
copyright ©right 2010-2021。
内容来自网络,如有侵犯请联系客服。zhit325@qq.com