replace None value in dictionary by python (1 key , 3 value)

Lewis :

I would like replace that "None" or "" (empty string) with "NoString" in my dictionary by python , i think a lot of time , but i can't finish it.

this is the dictionary:

{
'Column0':['ID','Company','Name'],
'Column1':[293193,'Exist','Robort Car'],
'Column2':[None,None,""],
'Column3':[None,"Close",None],
'Column4':["",None,None]
}

maybe i will use for and if ,please help me

Muhammad Moiz Ahmed :

I think the key here is to understand how to modify values of of a list. a simple for loop over a list would not modify / update values of a list. To do this, one has to use Enumerate, and access the element by index, to be able to successfully modify the value. I would also propose to use isinstance just out of my practice, because imagine a value not to be a list, then I do not want my code to break, and it is not that difficult to secure the code by using isinstance(...,list) per say.

Here is a more basic, easy to understand solution.

d = {
'Column0':['ID','Company','Name'],
'Column1':[293193,'Exist','Robort Car'],
'Column2':[None,None,""],
'Column3':[None,"Close",None],
'Column4':["",None,None]
}

print(d)

for k in d.keys():
    l = d[k]
    if isinstance(l,list):
        for idx, i in enumerate(l):
            if l[idx] is None:
                l[idx] = "NoString"

print(d)

and the output:

enter image description here

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398756&siteId=1