user2879373
user2879373

Reputation: 73

Storing list data into a dictionary

I'm trying to convert some data in a list to a dictionary. However, I want this dictionary to have multiple keys with multiple values, for example:

The list:

    titles = [ "title1", "title2" ]
    ids = [ 1, 2 ]

The dictionary:

    dictionary = { "title" : "title1", "title2", "id" : 1, 2 }

Sort of like a JSON idea... There are actually quite a few entries in the lists, so I can't do them each manually. I could use a loop, I suppose?

Upvotes: 0

Views: 110

Answers (4)

linbo
linbo

Reputation: 2431

Another solution is using dict setdefault function

>>> d = {}
>>> d.setdefault('title', []).append('title1')
>>> d.setdefault('title', []).append('title2')
>>> d
{'title': ['title1', 'title2']}

Upvotes: 0

realli
realli

Reputation: 1040

you can also try this:

>>> titles = ["t1","t2"]
>>> ids = [1,2]
>>> dct = {"titles": titles, "ids":ids}
>>> dct
{'titles': ['t1', 't2'], 'ids': [1, 2]}

Upvotes: 0

TerryA
TerryA

Reputation: 59974

You probably want a defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d['title'].append('title1')
>>> d['title'].append('title2')
>>> print d
defaultdict(<type 'list'>, {'title': ['title1', 'title2']})

In your case, however, you can simply do:

dictionary = {'title':titles, 'id':ids}

Upvotes: 2

user6993
user6993

Reputation: 41

You can link items together using tuples also if you'd prefer (using parentheses). This way you can access multiple items with one key. I don't quite know if this is what you're looking for, but I hope it helps.

dictionary = { "title" : ("title1", "title2"), "id" : (1, 2) }
#dictionary[title][0] returns "title1"
#dictionary[title][1] returns "title2"

More info on tuples: http://docs.python.org/release/1.5.1p1/tut/tuples.html

Upvotes: 1

Related Questions