2012-02-07 227 views
1
'state_license': {u'License ': u'29393, 25633', 
        u'Expiration': u'08-01-2012, 04-02-2012', 
        u'Trade': u'Registered Contractor, Plumber'} 

如何將'29393, 25633'轉換爲列表?將字典值轉換爲列表?

回答

4
>>> state_license = {u'License ': u'29393, 25633', 
...     u'Expiration': u'08-01-2012, 04-02-2012', 
...     u'Trade': u'Registered Contractor, Plumber'} 
>>> {key: value.split(", ") for key, value in state_license.items()} 
{u'License ': [u'29393', u'25633'], 
u'Expiration': [u'08-01-2012', u'04-02-2012'], 
u'Trade': [u'Registered Contractor', u'Plumber']} 
+0

@RikPoggi:謝謝你修復錯字! – 2012-02-07 10:36:16

0

您可以使用此split method

>>> u'29393, 25633'.split() 
[u'29393,', u'25633'] 

如果你有你的大的字典在info,你想就地值轉換,然後做

info['state_license']['License'] = info['state_license']['License'].split() 
3

隨着split()

>>> '29393, 25633'.split(', ') 
['29393', '25633'] 

現在還不清楚,但你似乎有雙重嵌套的字典,是這樣的:

d = {'state_license': {'License ': '29393, 25633', 
         'Expiration': '08-01-2012, 04-02-2012', 
         'Trade': 'Registered Contractor, Plumber'}} 

要轉換:

nested = d['state_license'] 
for k,v in nested.iteritems(): 
    nested[k] = v.split(', ') 

""" 
{'state_license': {'License ': ['29393', '25633'], 
        'Expiration': ['08-01-2012', '04-02-2012'], 
        'Trade': ['Registered Contractor', 'Plumber']}} 
""" 
+0

咦?爲什麼downvote?這是OP實際問題的確切答案。 – 2012-02-07 10:35:21

+0

@Tim:是的,這很奇怪......我試圖改進它:) – 2012-02-07 10:45:25

-2

現在。 (!不要)如果你想成爲一個敢魔鬼,你可以這樣做:

>>> eval('[' + u'29393, 25633' + ']') 
[29393, 25633] 

不過...。那取決於你知道什麼是在該列表中。這也將打破其他元素:

>>> eval('[' + u'08-01-2012, 04-02-2012' + ']') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<string>", line 1 
    [08-01-2012, 04-02-2012] 
    ^
SyntaxError: invalid token 

所以,堅持str.split()方法)

0

如果有鑰匙'state_license'字典中被稱爲d

[d.__setitem__(k,v.split(", ")) for k,v in d['state_license'].items()] 
0

如果我沒有弄錯,eval()翻譯代碼來生成Python字節碼,然後在Python虛擬機中執行它,它是w AY比普通str.split功能較慢:

help(str.split) 

在事實上,我與分裂「」而不是「」,然後剝離的每個項目,例如(Python3.x字典理解):

{k: [x.strip() for x in v.split(',')] for k, v in dictionary['state_license'].items()}