111 发表于 2018-8-4 06:24:38

Python中的字典及举例

  字典
  字典是python中的唯一的映射类型(哈希表)
  字典对象是可变的,但是字典的键必须使用不可变对象,一个字典中可以使用不同类型的键值。
  字典的方法
  keys()
  values()
  items()
  举例如下:
  In : dic = {}
  In : type(dic)
  Out: dict
  In : dic = {'a':1,1:123}
  In : dic
  Out: {1: 123, 'a': 1}
  In : dic = {'a':1,1:123,('a','b'):'hello'}
  In : dic = {'a':1,1:123,('a','b'):'hello',:1}
  ---------------------------------------------------------------------------
  TypeError                                 Traceback (most recent call last)
  <ipython-input-15-4fc52e86cb96> in <module>()
  ----> 1 dic = {'a':1,1:123,('a','b'):'hello',:1}
  TypeError: unhashable type: 'list'
  In : len(dic)
  Out: 3
  In : dic.keys()
  Out: ['a', 1, ('a', 'b')]
  In : dic.values()
  Out:
  In : dic.get('a')
  Out: 1
  In : dic
  Out: {1: 123, 'a': 1, ('a', 'b'): 'hello'}
  In : dic
  Out: 123
  更改字典内value:
  In : dic['a'] = 2
  In : dic
  Out: {1: 123, 'a': 2, ('a', 'b'): 'hello'}
  查看是不是在字典里
  In : 'b' in dic
  Out: False
  In : 'a' in dic
  Out: True
  In : dic.has_key('a')
  Out: True
  In : dic.has_key('b')
  Out: False
  变为列表:
  In : dic.items()
  Out: [('a', 2), (1, 123), (('a', 'b'), 'hello')]
  In : dic
  Out: {1: 123, 'a': 2, ('a', 'b'): 'hello'}
  复制字典:
  In : dic1 = dic.copy()
  In : dic1
  Out: {1: 123, 'a': 2, ('a', 'b'): 'hello'}
  In : dic
  Out: {1: 123, 'a': 2, ('a', 'b'): 'hello'}
  删除字典内容:
  In : dic.pop(1)
  Out: 123
  In : dic
  Out: {'a': 2, ('a', 'b'): 'hello'}
  In : dic.pop(2)
  ---------------------------------------------------------------------------
  KeyError                                  Traceback (most recent call last)
  <ipython-input-39-9f97239cddce> in <module>()
  ----> 1 dic.pop(2)
  KeyError: 2
  In :
  更新字典,两个字典更新为一个:
  In : dic1 = {1:1,2:2}
  In : dic.update(dic1)
  In : dic1
  Out: {1: 1, 2: 2}
  In : dic
  Out: {1: 1, 2: 2, 'a': 2, ('a', 'b'): 'hello'}
  创建字典:
  dic = {}
  dic = dict()
  help(dict)
  dict((['a',1],['b',2]))
  dict(a=1,b=2)
  fromkeys(),字典元素有相同的值时,默认为None.
  ddict = {}.formkeys(('x','y'),100)
  dic.fromkeys(range(100),100)
  In : dic.fromkeys('abc')
  Out: {'a': None, 'b': None, 'c': None}
  In : dic = {}
  In : dic
  Out: {}
  In : dict()
  Out: {}
  In : dict(x=10,y=100)
  Out: {'x': 10, 'y': 100}
  In : dict([('a',10),('b',20)])
  Out: {'a': 10, 'b': 20}
  访问字典:
  In : dic={1:1,2:3,3:5}
  In : dic
  Out: {1: 1, 2: 3, 3: 5}
  In : dic
  Out: 3
  In : dic.items()
  Out: [(1, 1), (2, 3), (3, 5)]
  for循环访问:
  In : for i in dic:
  ....:   print i,dic
  ....:
  1 1
  2 3
  3 5
  In : for i in dic:
  ....:   print &quot;%s,%s&quot; % (i,dic)
  ....:
  1,1
  2,3
  3,5
  In : dic
  Out: {1: 1, 2: 3, 3: 5}
  In : dic
  Out: {1: 1, 2: 3, 3: 5}
  In : for k,v in dic.items():print k,v
  1 1
  2 3
  3 5
  字典练习
  写出脚本,根据提示输入内容,并输入到字典中。
  1种:
  # cat dict.py
  #!/usr/bin/python
  #Author is fengXiaQing
  #date 2017.12.22
  info = {}
  name = raw_input(&quot;Please input name:&quot;)
  age = raw_input(&quot;Please input age:&quot;)
  gender = raw_input(&quot;Please input (M/F):&quot;)
  info['name'] = name
  info['age'] = age
  info['gender'] = gender
  print info
  #
  # python dict.py
  Please input name:fxq
  Please input age:20
  Please input (M/F):M
  {'gender': 'M', 'age': '20', 'name': 'fxq'}
  #
  2.种
  #!/usr/bin/python
  #Author is fengXiaQing
  #date 2017.12.22
  info = {}
  name = raw_input(&quot;Please input name:&quot;)
  age = raw_input(&quot;Please input age:&quot;)
  gender = raw_input(&quot;Please input (M/F):&quot;)
  info['name'] = name
  info['age'] = age
  info['gender'] = gender
  print info.items()
  # python dict.py
  Please input name:fxq
  Please input age:22
  Please input (M/F):M
  [('gender', 'M'), ('age', '22'), ('name', 'fxq')]
  #
  3.种
  #!/usr/bin/python
  #Author is fengXiaQing
  #date 2017.12.22
  info = {}
  name = raw_input(&quot;Please input name:&quot;)
  age = raw_input(&quot;Please input age:&quot;)
  gender = raw_input(&quot;Please input (M/F):&quot;)
  info['name'] = name
  info['age'] = age
  info['gender'] = gender
  for i in info.items():
  print i
  print &quot;main end&quot;
  # python dict.py
  Please input name:fxq
  Please input age:22
  Please input (M/F):M
  ('gender', 'M')
  ('age', '22')
  ('name', 'fxq')
  main end
  #
  4.种
  #!/usr/bin/python
  #Author is fengXiaQing
  #date 2017.12.22
  info = {}
  name = raw_input(&quot;Please input name:&quot;)
  age = raw_input(&quot;Please input age:&quot;)
  gender = raw_input(&quot;Please input (M/F):&quot;)
  info['name'] = name
  info['age'] = age
  info['gender'] = gender
  for k,v in info.items():
  print k,v
  print &quot;main end&quot;
  # python dict.py
  Please input name:fxq
  Please input age:22
  Please input (M/F):M
  gender M
  age 22
  name fxq
  main end
  #
  5.种
  #!/usr/bin/python
  #Author is fengXiaQing
  #date 2017.12.22
  info = {}
  name = raw_input(&quot;Please input name:&quot;)
  age = raw_input(&quot;Please input age:&quot;)
  gender = raw_input(&quot;Please input (M/F):&quot;)
  info['name'] = name
  info['age'] = age
  info['gender'] = gender
  for k,v in info.items():
  print &quot;%s:%s&quot; % (k,v)
  print &quot;main end&quot;
  # python dict.py
  Please input name:fxq
  Please input age:22
  Please input (M/F):M
  gender:M
  age:22
  name:fxq
  main end
  #
  6.种
  #!/usr/bin/python
  #Author is fengXiaQing
  #date 2017.12.22
  info = {}
  name = raw_input(&quot;Please input name:&quot;)
  age = raw_input(&quot;Please input age:&quot;)
  gender = raw_input(&quot;Please input (M/F):&quot;)
  info['name'] = name
  info['age'] = age
  info['gender'] = gender
  for k,v in info.items():
  print &quot;%s&quot; % k
  print &quot;main end&quot;
  # python dict.py
  Please input name:fxq
  Please input age:22
  Please input (M/F):M
  gender
  age
  name
  main end
  #
  练习:
  1. 现有一个字典dict1 保存的是小写字母a-z对应的ASCII码
  dict1 = {'a': 97, 'c': 99, 'b': 98, 'e': 101, 'd': 100, 'g': 103, 'f': 102, 'i': 105, 'h': 104, 'k': 107, 'j': 106, 'm': 109, 'l': 108, 'o': 96, 'n': 110, 'q': 113, 'p': 112, 's': 115, 'r': 114, 'u': 117, 't': 116, 'w': 119, 'v': 118, 'y': 121, 'x': 120, 'z': 122}
  1) 将该字典按照ASCII码的值排序
  print sorted(dict1.iteritems(), key=lambda d:d, reverse=False)
  2) 有一个字母的ASCII错了,修改为正确的值,并重新排序
  dict1['o']=111
  print sorted(dict1.iteritems(), key=lambda d:d, reverse=False)
  2. 用最简洁的代码,自己生成一个大写字母 A-Z 及其对应的ASCII码值的字典dict2(使用dict,zip,range方法)
  dict2 = dict(zip(string.uppercase,range(65,92)))
  print dict2
  3. 将dict2与第一题排序后的dict1合并成一个dict3
  dict3 = dict(dict1, **dict2)
  # dict3 = dict(dict1, **dict2)等同于下面的两行代码
  # dict3 = dict1.copy()
  # dict3.update(dict2)
  print dict3
页: [1]
查看完整版本: Python中的字典及举例