开发者

How to put 2 lists into 1 Dictionary in Python?

开发者 https://www.devze.com 2023-01-14 07:50 出处:网络
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\']

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号