I have a tuple, like ('key1', 'value1')
that I want to add that to a dictionary so it is like {'key1': 'value1'}
but not doing something like dictionary[t[0]] = t[1]
.
The context is as follows, I have a recurrence rule that looks like:
FREQ=WEEKLY;UNTIL=20120620T233000Z;INTERVAL=2;BYDAY=WE,TH
And I want to have a dict like:
recurrence = {
'freq' : 'weekly',
'until' : '20120620T233000Z',
'interval' : '2',
'byday' : 'we,th'
}
And I'm doing something like this:
for rule in recurrence.split(';'):
r = rule.split('=')
rules[r[0]] = r[1]
And I don't like it at all. Is there a more pythonic way of doing it?
Use a comprehension:
rules.update(rule.split('=', 1) for rule in recurrence.split(';'))
This is if the dict rules
already exists; otherwise use
rules = dict(rule.split('=', 1) for rule in recurrence.split(';'))
This works because the dict
constructor and dict.update
both accept an iterator yielding key/value pairs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With