I’m creating a mail “bot” for one of my web services that will periodically collect a queue of e-mail messages to be sent from a PHP script and send them via Google’s SMTP servers. The PHP script returns the messages in this format:
test@example.com:Full Name:shortname\ntest2@example.com:Another Full Name:anothershortname\ntest@example.com:Foo:bar
I need to “convert” that into something like this:
{
"test@example.com": [
[
"Full Name",
"shortname"
],
[
"Foo",
"bar"
]
],
"test2@example.com": [
[
"Another Full Name",
"anothershortname"
]
]
}
Notice I need to have only one key per e-mail, even if there are multiple instances of an address. I know I can probably do it with two consecutive loops, one to build the first level of the dictionary and the second to populate it, but there should be a way to do it in one shot. This is my code so far:
raw = "test@example.com:Full Name:shortname\ntest2@example.com:Another Full Name:anothershortname\ntest@example.com:Foo:bar"
print raw
newlines = raw.split("\n")
print newlines
merged = {}
for message in newlines:
message = message.split(":")
merged[message[0]].append([message[1], message[2]])
print merged
I’m getting a KeyError on the last line of the loop, which I take to mean the key has to exist before appending anything to it (appending to a nonexistent key will not create that key).
I’m new to Python and not really familiar with lists and dictionaries yet, so your help is much appreciated!
You are right about the error. So you have to check if the key is present.
'key' in dictreturnsTrueif'key'is found indict, otherwiseFalse. Implementing this, here’s your full code (with the debugging print statements removed):Notice the extra brackets for the nested list on the second last line.