首页 > 编程知识 正文

python制作字典程序,Python字典的创建

时间:2023-12-27 22:27:41 阅读:326540 作者:SAWH

本文目录一览:

求助python大神,编写程序,实现以下功能:(1)创建空字典

# 创建 dic_student 字典

dic_student = dict()

# 依次输入姓名和年龄,存入dic_student字典,共 5 组数据

for i in range(5):

name = input().strip()

age = int(input().strip())

dic_student.update({name: age})

# 按行输出,中间用 t 隔开

for key, value in dic_student.items():

print(key, value, sep='t')

python创建字典有多少种方法

两种

法一使用赋值符号直接创建字典

法二使用内置函数dict创建字典

python 怎样创建一个字典

1.传统的文字表达式:

d={'name':'Allen','age':21,'gender':'male'} d

{'age': 21, 'name': 'Allen', 'gender': 'male'}123

如果你可以事先拼出整个字典,这种方式是很方便的。

2.动态分配键值:

d={} d['name']='Allen' d['age']=21 d['gender']='male' d

{'age': 21, 'name': 'Allen', 'gender': 'male'}123456

如果你需要一次动态地建立一个字典的一个字段,那么这种方式比较合适。

字典与列表不同,不能通过偏移量进行复制,只能通过键来读取或赋值,所以也可以这样为字典赋值,当然访问不存在的键会报错:

d[1]='abcd' d

{1: 'abcd', 'age': 21, 'name': 'Allen', 'gender': 'male'} d[2]

Traceback (most recent call last):

File "pyshell#9", line 1, in module

d[2]

KeyError: 212345678

3.字典键值表

c = dict(name='Allen', age=14, gender='male') c

{'gender': 'male', 'name': 'Allen', 'age': 14}123

因为这种形式语法简单,不易出错,所以非常流行。

这种形式所需的代码比常量少,但是键必须都是字符串才行,所以下列代码会报错:

c = dict(name='Allen', age=14, gender='male', 1='abcd')SyntaxError: keyword can't be an expression12

4.字典键值元组表

e=dict([('name','Allen'),('age',21),('gender','male')]) e

{'age': 21, 'name': 'Allen', 'gender': 'male'}123

如果你需要在程序运行时把键和值逐步建成序列,那么这种方式比较有用。

5.所有键的值都相同或者赋予初始值:

f=dict.fromkeys(['height','weight'],'normal') f

{'weight': 'normal', 'height': 'normal'}

python字典中如何创建字典

python---创建字典的方式

1、用{}创建字典

代码:

x = {"a":"1", "b":"2"}

print x

输出:

{'a': '1', 'b': '2'}

2、用内置函数dict()

(1)、入参为类似a="1"的键值对

代码:

x = dict(a="1", b="2")

print x

输出:

{'a': '1', 'b': '2'}

(2)、入参为一个元组,元组内部是一系列包含两个值的元组,例如(("a", "1"), ("b", "2"))

代码:

x = dict((("a", "1"), ("b", "2")))

print x

输出

{'a': '1', 'b': '2'}

(3)、入参为一个元组,元组内部是一系列包含两个值的列表,例如(["a", "1"], ["b", "2"])

代码:

x = dict((["a", "1"], ["b", "2"]))

print x

输出:

{'a': '1', 'b': '2'}

(4)、入参为一个列表,列表内部是一系列包含两个值的元组,例如[("a", "1"),("b", "2")]

代码:

x = dict([("a", "1"),("b", "2")])

print x

输出:

{'a': '1', 'b': '2'}

(5)、入参为一个列表,列表内部是一系列包含两个值的列表,例如[["a", "1"],["b", "2"]]

代码:

x = dict([["a", "1"],["b", "2"]])

print x

输出:

{'a': '1', 'b': '2'}

注意:

对于a="1"的方式初始化字典,字典的key只能为字符串,并且字符串不用加引号

对于dict内置函数初始化当入参是一个元组时,例如1)、2),元组内部的两元素元组或者列表至少为两个,否则会出错

3、用户fromkeys方法创建字典

代码:

dict.fromkeys(("a", "b"), 1)

print x

输出:

{'a': 1, 'b': 1}

入参可以的第一个参数是一个列表或者元组,里边的值为key,第二个参数是所有key的value值

怎么用PYTHON编辑字典程序 急求

#/usr/bin/python

if __name__ == '__main__':

#read your dict file in a variable

d = {'a':'a's meaning here', 'b':'xx'}

while True:

w = raw_input("please input the word: ");

if w not in d:

print "%s not found" % w

else:

print "%s: %s" % (w, d[w])

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。