Reputation: 31
Working in Python and I've tried a number of different variations but this is my latest. I'm trying to convert "user" list to a dictionary that looks like this:
{
"Grae Drake": 98110,
"Bethany Kok": None,
"Alex Nussbacher": 94101,
"Darrell Silver": 11201,
}
It would show the user's name and zip code, but one user is missing a zip code so I want it to show 'None' where the zip code is missing. Converting isn't the issue, but I'm trying to make it more dynamic in that it will recognize the missing zip code and input 'None' instead.
users = [["Grae Drake", 98110], ["Bethany Kok"], ["Alex Nussbacher", 94101], ["Darrell Silver", 11201]]
def user_contacts():
for name, z in users:
[None if z is None else z for z in users]
user_dict = dict(users)
return user_dict
Upvotes: 3
Views: 40
Reputation: 195553
One possible solution:
users = [["Grae Drake", 98110], ["Bethany Kok"], ["Alex Nussbacher", 94101], ["Darrell Silver", 11201]]
d = dict((u + [None])[:2] for u in users)
print(d)
Prints:
{'Grae Drake': 98110, 'Bethany Kok': None, 'Alex Nussbacher': 94101, 'Darrell Silver': 11201}
Upvotes: 2