JackLi07

python之字典操作

1.字典的增操作(三种)

  1. dic[key] = value   直接添加,如已存在对应的key,则修改相应的value
  2. D.setdefault(k,d])   return D.get(k,d), also set D[k]=d if k not in D
  3. D.update(**F)   upadate D:   for k in F:  D[k] = F[k]

2.字典的删操作(四种)

  1. pop(key): remove key-value and return value in dict.
  2. popitem():  remove random key-value and return value in dict.
  3. del:   delete dict or dic[key] using del
  4. clear():  remove all key-value from dict

3.字典的改操作(两种)

  1. dic[key] = value   直接添加,如已存在对应的key,则修改相应的value
  2. D.update(**F)   upadate D:   for k in F:  D[k] = F[k]

4.字典的查操作(两种)

  1. dic[key]   using dic[key]  directly,Raise a KeyError if key not in dic
  2. get(key) return dic[key]  if key in dic,otherwise return None

5.特殊方法(三种)

  1. keys()
  2. values()
  3. items()
dic = {"4": "6464", True: False}
# 1.keys
print(dic.keys())
# 2.values
print(dic.values())
# 3.items
print(dic.items())

for keys, values in dic.items():
    print(keys, values)

结果:

 --dict_keys(['4', True])
 --dict_values(['6464', False])
 --dict_items([('4', '6464'), (True, False)])
 --4 6464
 --True False

 

6*.fromkeys()

 fromkeys(seq[, value]):Returns a new dict with keys from iterable and values equal to value.
  • seq -- 字典键值列表。
  • value -- 可选参数, 设置键序列(seq)的值。
seq = ('Google', 'Runoob', 'Taobao')
dict = dict.fromkeys(seq)
print(dict)
--{'Google': None, 'Runoob': None, 'Taobao': None}

dict = dict.fromkeys(seq, 10)
--{'Google': 10, 'Taobao': 10, 'Runoob': 10}
seq = ["a", "b", "c", "d"]
value = [1, 2]
dict = dict.fromkeys(seq, value)
print(dict)
--{'a': [1, 2], 'b': [1, 2], 'c': [1, 2], 'd': [1, 2]}
dict["a"].append(3)
print(dict)
--{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3], 'd': [1, 2, 3]}
深坑

 

posted @ 2018-10-29 18:22  JackLi07  阅读(184)  评论(0编辑  收藏  举报