Add 2 tuple values ​​to dict as key: value

I have a tuple, for example ('key1', 'value1') , which I want to add to the dictionary, so it looks like {'key1': 'value1'} but does not do something like dictionary[t[0]] = t[1] .

The context is this: I have a repeat rule that looks like this:

 FREQ=WEEKLY;UNTIL=20120620T233000Z;INTERVAL=2;BYDAY=WE,TH 

And I want to have such a recorder:

 recurrence = { 'freq' : 'weekly', 'until' : '20120620T233000Z', 'interval' : '2', 'byday' : 'we,th' } 

And I am 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 to do this?

+7
source share
3 answers

Use insight:

 rules.update(rule.split('=', 1) for rule in recurrence.split(';')) 

This is if dict rules already exist; 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 dict.update key / value pairs.

+6
source

The dict function converts your tuple of tuples into a dictionary of keys: value. How about this

 t=((1,2),(3,4)) dict(t) {1:2,3:4} 
+1
source

dictionary usage:

 >>> strs="FREQ=WEEKLY;UNTIL=20120620T233000Z;INTERVAL=2;BYDAY=WE,TH" >>> dic={key: value for key, value in (rule.split("=") for rule in strs.split(";"))} >>> print(dic) {'BYDAY': 'WE,TH', 'FREQ': 'WEEKLY', 'INTERVAL': '2', 'UNTIL': '20120620T233000Z'} 
+1
source

All Articles