How do I load a dict from a list in python?
3 answers
myDict = {}
myLog = [['a', 917], ['b', 312], ['c', 303],['d', 212], ['a', 215],
['b', 212], ['c', 213], ['d', 202]]
# For each of the log in your input log
for log in myLog:
# If it is already exist, you append it
if log[0] in myDict:
myDict[log[0]].append(log[1])
# Otherwise you can create a new one
else:
myDict[log[0]] = [log[1]]
# Simple test to show it works
while True:
lookup = input('Enter your key: ')
if lookup in myDict:
print(myDict[lookup])
else:
print('Item not found.')
Sven Marnach's answer is smarter and better, but this version I am coming. I see the limitation of my solution.
+2
source to share