Home > Enterprise >  How to append Dictionary keys null values in a list?
How to append Dictionary keys null values in a list?

Time:07-01

I have a dictionary that has multiple keys and each key has multiple values in list format, if the keys have a Null value then the key should be appended to a list.

here is my dictionary:

{'XSTY':['21.01', '22.01'], 'STRY': ['31.01', None], 'SYER': ['34.21', None], 'HUHTY': [None, '45.22]}

and I am using this approach to append the value of the keys whose values are null in the list

final_dict = {'XSTY':['21.01', '22.01'], 'STRY': ['31.01', None], 'SYER': ['34.21', None], 'HUHTY': [None, '45.22]}
data = []
for in in final_dict.keys():
    if i == 'HUHTY':
        if len(final_dict[i]>0:
            data.append(i)
            print("Append Success")
        else:
            print("data did not append")

the above code is appending the data for this key only HUHTY', but it should append the data for STRY,SYER,HUHTYall of these keys whose values areNone` inside the list. Any kind of help will be appreciated.

I know that it's not appending the other keys due to this condition if i == 'HUHTY': please provide a better approach to do the same thing dynamically.

CodePudding user response:

Is this what you're looking for?

final_dict = {'XSTY':['21.01', '22.01'], 'STRY': ['31.01', None], 'SYER': ['34.21', None], 'HUHTY': [None, '45.22']}
data = [k for k,v in final_dict.items() for i in v if not i]    
print(data)

Output:

['STRY', 'SYER', 'HUHTY']

CodePudding user response:

Hope this help you

datas ={'XSTY':['21.01', '22.01'], 'STRY': ['31.01', None], 'SYER': ['34.21', None], 'HUHTY': [None, '45.22']}
data = []
for k,v in datas.items():
  for z in v:
    if (z) ==None:
      data.append(k)
print(data)
  • Related