我是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
dict
,因为它将用该名称掩盖内置函数。如果您有大量字典或列表,则可能需要修改数据。如果是这样,这可能是最有效的:
for key, value in di.items():
for i, e in enumerate(value):
if e is None: di[key][i]='None'