本博客主要说明python的字典基本的使用,在python中,字典使用的关键字是dict,使用的是{},下面我们通过一个具体的代码来看python字典类对象的功能和字典的帮助的详细信息,见实现的代码:
#!/usr/bin/env python
#coding:utf-8
dict1={'name':'wuya','age':20,'address':'xian'}
print u'查看字典所具备的功能:',dir(dict1)
print u'查看字典详细的帮助信息:\n',help(type(dict1))
见如上的代码执行后输出的内容:
C:\Python27\python.exe D:/git/Python/FullStack/Study/index.py
查看字典所具备的功能: ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
查看字典详细的帮助信息:
Help on class dict in module __builtin__:
class dict(object) |
dict() -> new empty dictionary | dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs | dict(iterable) -> new dictionary initialized as if via: | d = {} | for k, v in iterable: | d[k] = v | dict(**kwargs) -> new dictionary initialized with the name=value pairs | in the keyword argument list. For example: dict(one=1, two=2) |
| Methods defined here: |
| __cmp__(...) | x.__cmp__(y) <==> cmp(x,y) |
| __contains__(...) | D.__contains__(k) -> True if D has a key k, else False |
| __delitem__(...) | x.__delitem__(y) <==> del x[y] |
| __eq__(...) | x.__eq__(y) <==> x==y |
| __ge__(...) | x.__ge__(y) <==> x>=y |
| __getattribute__(...) | x.__getattribute__('name') <==> x.name |
| __getitem__(...) | x.__getitem__(y) <==> x[y] |
| __gt__(...) | x.__gt__(y) <==> x>y |
| __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature |
| __iter__(...) | x.__iter__() <==> iter(x) |
| __le__(...) | x.__le__(y) <==> x<=y |
| __len__(...) | x.__len__() <==> len(x) |
| __lt__(...) | x.__lt__(y) <==> x<y |
| __ne__(...) | x.__ne__(y) <==> x!=y |
| __repr__(...) | x.__repr__() <==> repr(x) |
| __setitem__(...) | x.__setitem__(i, y) <==> x[i]=y |
| __sizeof__(...) | D.__sizeof__() -> size of D in memory, in bytes |
| clear(...) | D.clear() -> None. Remove all items from D. |
| copy(...) | D.copy() -> a shallow copy of D |
| fromkeys(...) | dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. | v defaults to None. |
| get(...) | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. |
| has_key(...) | D.has_key(k) -> True if D has a key k, else False |
| items(...) | D.items() -> list of D's (key, value) pairs, as 2-tuples
|
| iteritems(...) | D.iteritems() -> an iterator over the (key, value) items of D |
| iterkeys(...) | D.iterkeys() -> an iterator over the keys of D |
| itervalues(...) | D.itervalues() -> an iterator over the values of D |
| keys(...) | D.keys() -> list of D's keys
|
| pop(...) | D.pop(k[,d]) -> v, remove specified key and return the corresponding value. | If key is not found, d is returned if given, otherwise KeyError is raised |
| popitem(...) | D.popitem() -> (k, v), remove and return some (key, value) pair as a | 2-tuple; but raise KeyError if D is empty. |
| setdefault(...) | D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D |
| update(...) | D.update([E, ]**F) -> None. Update D from dict/iterable E and F. | If E present and has a .keys() method, does: for k in E: D[k] = E[k] | If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v | In either case, this is followed by: for k in F: D[k] = F[k] |
| values(...) | D.values() -> list of D's values
|
| viewitems(...) | D.viewitems() -> a set-like object providing a view on D's items
|
| viewkeys(...) | D.viewkeys() -> a set-like object providing a view on D's keys
|
| viewvalues(...) | D.viewvalues() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes defined here: |
| __hash__ = None |
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T
None
Process finished with exit code 0
在如上输出的帮助信息中,可以看到dict类中有很多的方法,下面就通过具体的代码来说明字典类中这些方法的具体使用,见实现的代码:
#!/usr/bin/env python
#coding:utf-8
dict1={'name':'wuya','age':20,'address':'xian'}
#获取字典中指定的value值
print u'获取name对应的value值:',dict1['name']
#对字典默认循环,特别注意,字典默认循环的时候,输出的是key的值
for key in dict1:
print key
#循环获取字典中的所有值
for key,value in dict1.items():
print key,':',value
#获取字典所有的key值(注意获取后成一个字典)
print u'获取字典所有的key值:',dict1.keys(),type(dict1.keys())
#获取字典所有的value(注意获取后成一个字典)
print u'获取字典所有的value值:',dict1.values(),type(dict1.values())
#获取字典所有的键值对
print u'获取字典所有的键值对:',dict1.items(),type(dict1.items())
#判断键值是否在字典中
print u'判断name是否在dict1字典中:',dict1.has_key('name')
#利用字典的key生成新的字典
print u'使用fromkeys方法生成新的字典:',dict1.fromkeys(['name','age'],('wuya',18))
#对字典的内容进行更新
dict1['name']=u'无涯'
print u'更新后的字典内容:',dict1
在python中,列表,元组,字典,字符串之间是可以互相转换的,下面就通过具体的代码看这部分:
#!/usr/bin/env python
#coding:utf-8
list1=['name','age','address']
print u'把列表list1转换为字符串:',str(list1),u'类型为:',type(str(list1)) str='wuya name sex age'
print u'把字符串str转换为列表:',str.split(' '),'类型为:',type(str.split(' '))
print u'把列表list1转换为元组:',tuple(list1),'类型为:',type(tuple(list1))
tuple1=('android','ios','windows','firefoxos')
print u'把元组tuple1转换为字典:',list(tuple1),'类型为:',type(list(tuple1))
dict1={'name':'wuya','age':18,'address':'xian'}
print u'把字典dict1转换为列表:',list(dict1.items()),'类型为:',list(dict1.items())
list2=list(dict1.items())
print u'把列表转换为字典:',dict(list2),'类型为:',type(dict(list2))
print u'把列表list1转换为字典:',dict(enumerate(list1)),'类型为:',dict(enumerate(list1)