python - Dictionary and List -
while reading through file convert given data in format of key , value. (value age of person)
for example if file has data:
20120101,56years 20120102,45years 20120103,67years 20120104,38years .. , on until 20120131,21years.
i create dictionary , make date key ( in case let's line 1, key 20120101 ) , make value 56years.
when print out, separate dictionary every date. example:
{'20120101': ['56years']} {'20120102': ['45years']} {'20120103': ['67years']} {'20120104': ['38years']} since see every dictionary has same starting values 201201, how can make single dictionary has 1 key 201201 , values appended in list?
example:
{'201201': ['56years', '45years', '67years', '38years'...]}
you can use collections.defaultdict
from collections import defaultdict d = defaultdict(list) now, when key k , value v
d[k].append(v) after adding first key,value pair, dictionary might like:
{'201201' : [56years]} after reading key,value pair key "201201" , adding value d, dictionary like:
{'201201' : [56years,45years]}
Comments
Post a Comment