Skip to main content
 首页 » 编程设计

python之替换 Python 列表字典中的项目

2025年05月04日17Free-Thinker

我是 Python 和编程的新手,需要一些帮助来替换列表字典中的项目。我想在下面的字典中用 'None' 替换 None:

dict = {'Chester100': ['Caesar, Augustus', '05/10/2012', '09/09/2012', None], 
        'Rochester102': ['Henrich, Norton', '08/18/2014', '12/17/2014', None], 
        'Rochester100': ['Caeser, Julius', '08/18/2014', '12/17/2014', None], 
        'Rochester101': [None, None, None, '08/18/2012']} 

我的代码如下:

new_dict = {} 
 
for i in dict: #This accesses each dictionary key. 
    temp = [] 
    for j in dict[i]: #This iterates through the inner lists 
        if j is None: 
            temp.append('None') 
        else: 
            temp.append(j) 
        temp2 = {str(i):temp} 
        new_dict.update(temp2) 
 
    print(new_dict) 

产量

{'Chester100': ['Caesar, Augustus', '05/10/2012', '09/09/2012', 'None'],  
'Rochester102': ['Henrich, Norton', '08/18/2014', '12/17/2014', 'None'],  
'Rochester100': ['Caeser, Julius', '08/18/2014', '12/17/2014', 'None'],  
'Rochester101': ['None', 'None', 'None', '08/18/2012']} 

有没有办法用更少的代码行或使用列表理解或其他方法更有效地做到这一点?是否应该避免嵌套 for 循环(正如我在代码中所使用的那样)?谢谢。

使用 Python 3.4.1

请您参考如下方法:

使用字典理解:

>>> {k:[e if e is not None else 'None' for e in v] for k,v in di.items()} 
{'Rochester102': ['Henrich, Norton', '08/18/2014', '12/17/2014', 'None'], 'Rochester100': ['Caeser, Julius', '08/18/2014', '12/17/2014', 'None'], 'Rochester101': ['None', 'None', 'None', '08/18/2012'], 'Chester100': ['Caesar, Augustus', '05/10/2012', '09/09/2012', 'None']} 

并且不要将字典命名为 dict,因为它会用该名称屏蔽内置函数。


如果您有大量 字典或列表,您可能需要就地修改您的数据。如果是这样,这可能是最有效的:

for key, value in di.items(): 
    for i, e in enumerate(value): 
        if e is None: di[key][i]='None'