向字典中添加包含键和值的文件

2024-06-14 02:00:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,我想从中读取,它是这样的:

Warner, Bros, The Matrix, 5, 2.99

Sony, The Hobbit, 10, 3.99

Warner, Bros, Dark Knight, 4.99

我想从这个文件中创建一个字典,以华纳兄弟为键,其他的都是一个值。我还需要加入所有华纳兄弟在一起,使一个关键和关键的不同值将是电影的名称和数量(矩阵5)和价格。你知道吗

我是这样做的,我读了文件,然后把所有的东西都放到一个列表中,然后用这个列表创建一个字典,但我意识到,我将有多个相同品牌的键;例如华纳兄弟。我如何才能确保我只有一个品牌有多个值?你知道吗

谢谢!你知道吗


Tags: 文件the列表字典电影matrix关键兄弟
3条回答

请尝试以下操作。。。你知道吗

data = '''Warner, Bros, The Matrix, 5, 2.99
Sony, The Hobbit, 10, 3.99
Warner, Bros, Dark Knight, 1, 4.99''' # the 1 is missing from your example
                                      # is it a typo? or the text data has this kind
                                      # of errors that you should check?

                                      # you can read your data with a csv.reader
                                      # for this example I'll just split the lines

yourdata = dict() # or use the defaultdict approach

lines = data.split('\n')
for l in lines:
    fields = l.split(',')
    price = float(fields.pop(-1))
    quantity = int(fields.pop(-1))
    title = fields.pop(-1).strip()
    value = {'title': title, 'quantity': quantity, 'price': price}
    key = ' '.join(f.strip() for f in fields)
    if key not in yourdata:
        yourdata[key] = [value]
    else:
        yourdata[key].append(value)

print(yourdata)

或者为什么不用两部分的钥匙。。。你知道吗

    #  ...

    key = (' '.join(f.strip() for f in fields), title)
    value = {'quantity': quantity, 'price': price}
    yourdata[key] = value

    #  ...

使用defaultdict

from collections import defaultdict
d = defaultdict(list)
for key,value  in ([1,2],[3,4],[1,3],[4,2],[3,2]):
   d[key].append(value)
print d

要打印结果,可以使用这样的方法。我想你把你的资料当作口述,把电影公司的名字当作钥匙

for k in yourdata:
    print k            # format it as you need
    for movie in yourdata[k]:
        print ('\t'+movie['title'])
        print ('\t'+str(movie['quantity']))
        print ('\t'+str(movie['price']))
        print
    print

相关问题 更多 >