Printing Elements Of Dictionary Line By Line
Solution 1:
line.split()
splits on whitespace. You probably want line.split(':')
.
>>> "the:1".split()
['the:1']
>>> "the:1".split(':')
['the', '1']
Also note that
it = line.split(':')
k, v = it[0], it[1:]
can be simplified to
k, v = line.split(':')
edit: Well actually those two do different things, but as line.split()
should only have 2 elements, k, v = line.split(':')
will do what you want, whereas it[1:]
would return ['1']
instead of '1'
.
Though I guess to more gracefully handle parsing issues you could do:
it = line.split()
if len(it) != 2:
print"Error!"
k, v = it[0], it[1] # note it[1] and not it[1:]
Solution 2:
If you are trying to print the key values out of a dictionary in the same order as they appear in the file using a standard dict that won't work (python dict objects don't maintain order). Assuming you want to print by the value of the dicts values...
lines = ["the 1", "and 2"]
d = {}
for l inlines:
k, v = l.split()
d[k] = v
for key in sorted(d, key=d.get, reverse=True):
print":".join([key, d[key]])
assuming you can use lambda
and string concatenation.
lines = ["the 1", "and 2"]
d = {}
for l inlines:
k, v = l.split()
d[k] = v
for key in sorted(d, key=lambda k: d[k], reverse=True):
print key + ":" + d[key]
with out lambda
for value, key insorted([(d[k], k) for k in d], reverse=True):
print key + ":" + value
to make a function out of it
def lines_to_dict(lines):
return_dict = {}
for line inlines:
key, value = line.split()
return_dict[key] = value
return return_dict
if __name__ == "__main__":
lines = ["the 1", "and 2"]
print lines_to_dict(lines)
Solution 3:
As long as the key/value are both strings, then you can parse the dictionary and extract the elements. Note, since this doesn't actually create the dictionary, duplicate elements and the order is preserved - which you may wish to account for.
import ast
text = '{"the":"1", "and":"2"}'
d = ast.parse(text).body[0].value
for k, v in zip(d.keys, d.values):
print '{}:{}'.format(k.s, v.s)
Post a Comment for "Printing Elements Of Dictionary Line By Line"