2012-02-10 30 views

Trả lời

11
dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems()) 
+1

Lưu ý rằng ['iteritems'] (https://docs.python.org/2/library/stdtypes.html#dict.iteritems) [đã biến mất] (http://stackoverflow.com/questions/10458437/ what-is-the-different-giữa-dict-items-và-dict-iteritems) trong [Python 3] (https://www.python.org/download/releases/3.0/). Sử dụng ['items()'] (https://docs.python.org/3.7/library/stdtypes.html#dict.items) để thay thế. –

2
>>> d = {'Blog': '1', 'Discussions': '2', 'Followers': '21', 'Following': '21', 'Reading': '5'} 
>>> dict((k, int(v)) for k, v in d.iteritems()) 
{'Blog': 1, 'Discussions': 2, 'Followers': 21, 'Following': 21, 'Reading': 5} 
9

Bạn có thể sử dụng một dictionary comprehension :

{k:int(v) for k, v in d.iteritems()} 

trong đó d là từ điển có chuỗi.

+0

chỉ khi bạn sử dụng python 3 –

+1

@IvanVirabyan Bạn cũng có thể sử dụng từ điển comprehensions trong python 2.7 vì chúng đã được backported. – jcollado

+1

Trên thực tế, mã đó sẽ chỉ hoạt động trong Python 2.7. 'dict.iteritems' đã biến mất trong 3, vì' dict.items' không còn xây dựng danh sách nữa. – lvc

Các vấn đề liên quan