So this is the situation: I have 2 lists and want to put them in a dictionary.
Content ['This is Sams Content', 'This is someone's else content']
Author ['Sam', 'Someone Else']This is the dictionary I would like to create
Reviews [{'content': 'This is Sams Content', 'auth开发者_JS百科or' : 'Sam'} , {'content': 'This is someone's else content', 'author' : 'Someone Else'}
I hope you understand what the question is. Thanks for helping.
You're looking for zip I believe. Something like this:
reviews = [{'content': c, 'author': a} for c, a in zip(contentList, authorList)]
reviews = []
authors = ['sam', 'dave']
content = ['content by sam', 'content by dave']
for a, c in zip(authors, content):
reviews.append({'content':c, 'author':a})
print reviews
Assuming Content and Author are arrays as defined in the question, and assuming you want a single resulting dict:
d = {}
for i in range(len(Content)):
d[Content[i]] = Author[i]
content = ['This is Sams Content', 'This is someone\'s else content']
author = ['Sam', 'Someone Else']
reviews = []
for i in range(len(author)):
d = {
'content': content[i],
'author': author[i]
}
reviews.append(d)
for r in reviews:
print "Author: %s, content: %s" % (r['author'], r['content'])
EDIT for those who complained that range(len(...))
isn't sufficiently Pythonic (to which I say merely "seriously?"), here's the same solution using enumerate()
as suggested:
content = ['This is Sams Content', 'This is someone\'s else content']
author = ['Sam', 'Someone Else']
reviews = []
for i, elem in enumerate(author):
d = {
'content': content[i],
'author': elem,
}
reviews.append(d)
for r in reviews:
print "Author: %s, content: %s" % (r['author'], r['content'])
Personally I prefer the range(len(...))
solution over enumerate
, because accessing both arrays in the same style when creating the hash aids readability. zip
is still the most elegant solution though.
精彩评论