AAzeeze AAzeeze - 3 months ago 12x
Python Question

How to generate dict in Python?

I am a beginner in Python and i would like help:
My little script:

def get_link():

#My datas
dict = {}
dict['Label1'] = 'URL1'
dict['Label2'] = 'URL2'

return [{'label': l, 'url': u} for l, u in dict.iteritems()]


So, the problem is at the end. How to return the result as i want ?

a = {'label': 'Label1', 'uri': 'URL1'},{'label': 'Label2', 'uri':


As far as I can see from your question, there is always an association between a label and a value. So I suggest to store both in a single dictionary and not spread the information in two independent structures:

dict = {}
dict['Label1'] = 'URL1'
dict['Label2'] = 'URL2'

And to output it, you can use a simple loop:

[{'label': l, 'url': u} for l, u in dict.items()]

Of course this solution only makes sense, if for a given label there is only one URL. Otherwise, you need to turn your dictionary into a list to which you append label/url pairs.