Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a 2 value tuple to dict as key:value

Tags:

python

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?

like image 671
licorna Avatar asked Jun 12 '12 16:06

licorna


1 Answers

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.

like image 108
ecatmur Avatar answered Oct 12 '22 23:10

ecatmur