python字典操作
from gensim.models import Word2Vec
C:\Users\dell\Anaconda3\lib\site-packages\gensim\utils.py:1197: UserWarning: detected Windows; aliasing chunkize to chunkize_serial
  warnings.warn("detected Windows; aliasing chunkize to chunkize_serial")
Word2Vec?

字典创建、删除

aDict = {'server':'db.diveintopython3.org','database':'mysql'}
aDict
{'database': 'mysql', 'server': 'db.diveintopython3.org'}
#空字典
x = dict()# x={}
#键值表创建
keys = ['a','b', 'c', 'd']
values = [1, 2, 3, 4]
dictionary = dict(zip(keys,values))
dictionary
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 关键字参数创建字典
d = dict(name='Dong', age=39)
d
{'age': 39, 'name': 'Dong'}
# 以给定内容为“键”创建“值”为空的字典
aDict = dict.fromkeys(['name','age','sex'])
aDict
{'age': None, 'name': None, 'sex': None}
#推导式生成
{i:str(i) for i in range(1,5)}
{1: '1', 2: '2', 3: '3', 4: '4'}

字典元素的访问

aDict = {'age':39,'score':[98, 97],'name': 'Dong','sex':'male'}
def fun(x):
    if x in aDict:
        print(aDict[x])
    else:
        print('Not Exists.')
fun('Age')
Not Exists.
#使用异常处理结构
try:
    print(aDict['address'])
except:
    print('Not Exists. ')
Not Exists. 
  • 字典对象的get()方法
    • 用来指定“键”对应的“值”,并且允许指定该键不存在时返回特定的“值”
aDict.get('age')
39
#指定的“键”不存在时返回指定的默认值
aDict.get('address', 'Not Exists.')
'Not Exists.'
import string
import random
x = string.ascii_letters+string.digits
z = ''.join((random.choice(x) for i in range(1000))) #生成1000个随机字符
z
'NX90W2mXQN8XBosPihO3UJF6UfDIXFKwu1xKCYugYZuUZmHOWzThyt0yRDraBOdNiJuXGchgElrZshdpnYYtKcUO5Ytj9HoqJxQSPGMuvmf88mbuRXwNoUjtBx7plLl4i8ldDn88NQQqAS1bNfcAdzg0ufIA4m5XBpE8IOdqOf1JeI9wEGtRYV0WhmozeuJmfLxMWG5Miyrkc3FqfT5jDs0aK39HeLcozZdxrzwixFhd2epKS9vLvkuCeeqdX7R6y0scDWw64lIS6yJMPeIk3FIIjFuDcZIJ9Uc1pYrdFJa0lEUIHewO3TJMmrjqf5FroEHNJne1mO3wAq1cM8aKmFmd2EOJtSqqHPfBBT7KRs1mMpq9DSsqUyM03n5B8WVRARVGFj9fmWtjAzW6Yt4fR3kWQ2RBczq46mOeWBPYt9hKlIpPoT0dpKJ32Hqf944ZAnquIbgJbsRKUXHB5f7cRjw3yWLVQzfH07qrEYJMIMuxUT7TN20dwTiv7xopXaQHuw9EXQ9Lf9xypXyEd1K5zKLXLJY0Z1rKrFnp6vbJWDVvfrhL7c1rw5g2TcGjdRQIu2TSDQYsnPt6NqhbtyoWTB1hunttPOpHtpNGdMbVBAUURaOLos9tgAFwE7Bf6RkaY6pbaYk3VZHb5ULbU8wgpkDw0Rqx88OSMkBgsb3PsMpUPKl0iZ0Eni71G0YiR0b5y8borN2dH5kA8XJGDZiMcR5WEmwDJCgAr7QeYgF2yk1Tuwwhi7dkToAjlkRn57WxCMxVTj3ZWhS4MQbx0zrJsqMEzPKzxEgDCC0GrpiVtSFPDu1HaBL4mnH2aKeYmeooDPkzYFUCo2eZtYLIVMF7SgD6MZXWphzcEB77nAdmPJGYqeOeWRgcvNaF3VQZP0yIt3xGS1QE8h1mxU6L6kJ4e8drkzDTWb4IMHXKOOA9faMEQbUQp2K4agob5Rc4GB3hqwIKqMSwcWnzX3MHsM1KkEJDV5Z3SHVcZGN9MPeQ'
d = dict()
for ch in z: #遍历字符串统计频次
    d[ch] = d.get(ch, 0) + 1
for k, v in sorted(d.items()):#查看统计结果
    print(k,':',v)
0 : 20
1 : 17
2 : 13
3 : 18
4 : 13
5 : 16
6 : 13
7 : 16
8 : 16
9 : 16
A : 14
B : 17
C : 7
D : 18
E : 18
F : 17
G : 14
H : 18
I : 18
J : 22
K : 20
L : 14
M : 25
N : 13
O : 16
P : 16
Q : 17
R : 20
S : 14
T : 15
U : 18
V : 13
W : 20
X : 17
Y : 20
Z : 16
a : 13
b : 17
c : 19
d : 19
e : 18
f : 18
g : 14
h : 15
i : 12
j : 11
k : 16
l : 9
m : 19
n : 13
o : 16
p : 19
q : 21
r : 17
s : 13
t : 18
u : 17
v : 7
w : 19
x : 16
y : 13
z : 16
  • 字典对象的setdefault()方法
    • 用于返回指定“键”对应的“值”,如果字典中不存在该“键”,就添加一个新元素并设置该“键”对应的“值”(默认为None).
aDict.setdefault('address', 'SDIBT')#增加新的元素
'SDIBT'
aDict
{'address': 'SDIBT',
 'age': 39,
 'name': 'Dong',
 'score': [98, 97],
 'sex': 'male'}
  • 元素的添加删除、修改
aDict['age'] = 35 #修改
aDict['bb'] = 'nana' #添加
aDict
{'address': 'SDIBT',
 'age': 35,
 'bb': 'nana',
 'name': 'Dong',
 'score': [98, 97],
 'sex': 'male'}
  • 字典对象的update()方法
    • 可以将另一个字典的“键:值”一次性全部添加到当前字典对象;
    • 如果两个字典中存在相同的的“键”,则以另一个字典中的“值”为准对当前字典进行更新。
aDict.update({'a':97,'age':100}) #修改‘age’的值,同时添加新元素'a':97
aDict
{'a': 97,
 'address': 'SDIBT',
 'age': 100,
 'bb': 'nana',
 'name': 'Dong',
 'score': [98, 97],
 'sex': 'male'}
#删除元素
del aDict['age']
aDict
{'a': 97,
 'address': 'SDIBT',
 'bb': 'nana',
 'name': 'Dong',
 'score': [98, 97],
 'sex': 'male'}
  • pop()和popitem()方法可以弹出并删除指定元素。
aDict.popitem() #弹出一个元素,对空字典会抛出异常
('a', 97)
aDict.pop('sex') #弹出指定键对应的元素
'male'
aDict
{'address': 'SDIBT', 'bb': 'nana', 'name': 'Dong', 'score': [98, 97]}
  • clear()方法清空字典,copy()返回字典对象的浅复制

标准库collections中与字典有关的类

  • orderedDict类
    • 记住元素插入顺序的字典
import collections
x = collections.OrderedDict() #有序字典
x['a'] = 3
x['b'] = 5
x['c'] = 8
x
OrderedDict([('a', 3), ('b', 5), ('c', 8)])
  • defaultdict类:
    • 创建defaultdict对象时,传递的参数表示字典中值的类型。
import string
import random
x = string.ascii_letters + string.digits + string.punctuation
z = ''.join([random.choice(x) for i in range(1000)])
from collections import defaultdict
frequences = defaultdict(int) #所有值默认为0
frequences
defaultdict(int, {})
for item in z:
    frequences[item] += 1 #修改每个字符的频次
frequences.items() 
dict_items([('H', 11), ('k', 8), ('#', 12), ('z', 11), ('e', 16), ('Z', 12), ('8', 12), ('_', 19), ('r', 12), ('{', 7), ('0', 15), ('o', 11), ('2', 8), ('@', 13), ('w', 11), ('>', 5), ('1', 14), ('g', 12), ('*', 13), ('-', 10), ('.', 10), ('|', 9), ('u', 14), ('V', 13), ('q', 9), ('n', 6), ('A', 15), ('h', 11), (')', 11), ('Q', 19), ('!', 5), ('x', 17), ('J', 9), ('U', 9), ('<', 14), ('F', 8), ('9', 10), ('6', 12), ('v', 15), ('7', 9), ('y', 10), ('W', 7), ('m', 12), ('l', 7), ('s', 14), ('B', 10), (']', 9), ('~', 13), ('`', 6), ('d', 11), ('N', 11), ('C', 8), ('M', 9), ('+', 13), ('Y', 12), (',', 10), ('f', 9), ('[', 12), ('G', 11), ('c', 9), (';', 13), ('$', 7), ("'", 8), ('S', 12), ('i', 14), ('p', 7), ('b', 14), ('j', 11), (':', 6), ('\\', 9), ('%', 11), ('D', 14), ('E', 10), ('3', 11), ('?', 11), ('O', 11), ('5', 11), ('}', 11), ('=', 9), ('T', 11), ('4', 7), ('&', 16), ('a', 13), ('^', 7), ('"', 6), ('L', 5), ('t', 13), ('I', 10), ('(', 10), ('K', 4), ('P', 9), ('/', 9), ('X', 12), ('R', 8)])
games = defaultdict(list)
games
defaultdict(list, {})
games['name'].append('ZC')
games['name'].append('PCX')
games['score'].append(90)
games['score'].append(88)
games
defaultdict(list, {'name': ['ZC', 'PCX'], 'score': [90, 88]})
  • Counter类:频次统计
from collections import Counter
frequences = Counter(z)
frequences.items()
dict_items([('H', 11), ('k', 8), ('#', 12), ('z', 11), ('e', 16), ('Z', 12), ('8', 12), ('_', 19), ('r', 12), ('{', 7), ('0', 15), ('o', 11), ('2', 8), ('@', 13), ('w', 11), ('>', 5), ('1', 14), ('g', 12), ('*', 13), ('-', 10), ('.', 10), ('|', 9), ('u', 14), ('V', 13), ('q', 9), ('n', 6), ('A', 15), ('h', 11), (')', 11), ('Q', 19), ('!', 5), ('x', 17), ('J', 9), ('U', 9), ('<', 14), ('F', 8), ('9', 10), ('6', 12), ('v', 15), ('7', 9), ('y', 10), ('W', 7), ('m', 12), ('l', 7), ('s', 14), ('B', 10), (']', 9), ('~', 13), ('`', 6), ('d', 11), ('N', 11), ('C', 8), ('M', 9), ('+', 13), ('Y', 12), (',', 10), ('f', 9), ('[', 12), ('G', 11), ('c', 9), (';', 13), ('$', 7), ("'", 8), ('S', 12), ('i', 14), ('p', 7), ('b', 14), ('j', 11), (':', 6), ('\\', 9), ('%', 11), ('D', 14), ('E', 10), ('3', 11), ('?', 11), ('O', 11), ('5', 11), ('}', 11), ('=', 9), ('T', 11), ('4', 7), ('&', 16), ('a', 13), ('^', 7), ('"', 6), ('L', 5), ('t', 13), ('I', 10), ('(', 10), ('K', 4), ('P', 9), ('/', 9), ('X', 12), ('R', 8)])
frequences.most_common(1)#返回出现次数最多的一个字符及其频率
[('_', 19)]
frequences.most_common(3)#前三个
[('_', 19), ('Q', 19), ('x', 17)]
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NockinOnHeavensDoor/article/details/80321586
个人分类: python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

python字典操作

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭