【问题标题】:file to dictionary:value is a dictionary where the key is repeated文件到字典:值是重复键的字典
【发布时间】:2014-04-24 07:32:24
【问题描述】:

我打开一个包含以下内容的文件:

TransactionNo   Date        CustomerId      PurchasePairs
-------------   ----        ----------      -------------
1               09-04-2014  barakobama      potatoes:2.67,sugar:1.98,cereal:5.99,crisps:1.09
2               11-04-2014  barakobama      parsley:0.76,cereal:3.22
3               11-04-2014  vladimirputin   bread:0.66,milk:2.87,parsley:1.33

我想要这样的输出字典:

{'milk': {'vladimirputin': 2.87}, 'cereal': {'barakobama': 9.21},
'bread': {'vladimirputin': 0.66}, 'potatoes': {'barakobama': 2.67}, 
'sugar': {'barakobama': 1.98}, 'parsley': {'vladimirputin': 1.33,

我已经这样做了:

 C={}
file=open(fileNameStr,'r')


for line in file:
    if line[0].isdigit():
        fields = line.split()

【问题讨论】:

  • 为什么你回来的代码比your previous "attempt"还要少?
  • 它的代码相同,现在更清楚了
  • 您已经有了答案,为什么要提出这个新问题?为什么您没有使用该答案,甚至没有尝试修改它?
  • 因为我没有得到我想要的输出
  • 所以修改你想要的输出的代码,或者至少尝试这样做。如果上一个问题有误,请编辑。如果答案有误,请评论。我注意到您还有另一个earlier question,您也忽略了他的答案,那么为什么有人要费心回答这个问题呢?

标签: python file dictionary key


【解决方案1】:
c = {}
f = open(fileNameStr)
for line in f:
    if not line[0].isdigit(): continue
    transactionNo, _date, customerId, purchasePairs = line.split()
    for pair in purchasePairs.split(','):
        productName, price = pair.split(':')
        if productName in c:
            c[productName][customerId] = float(price)
        else:
            c[productName] = {customerId: float(price)}

您必须处理一种情况:即客户多次购买相同的东西。 希望这段代码会有所帮助。

【讨论】:

  • 只是输出 'cereal' 的区别:{'barakobama': 9.21}
【解决方案2】:
#!/usr/bin/python3

final_products = dict()

file_name = "myfile"
try:
    # it's better not to use reserved name like 'file'
    # fhd, for example, is better
    # you might want to remove encoding='utf-8' depending on your python version (2 or 3) :
    fhd = open(file_name, 'rt', encoding='utf-8') 
except:
    # here we cannot read the file
    raise
else:
    # ok, file is opened
    for line in fhd:
        if line[0].isdigit():
            fields = line.split()
            # there should be exactly 4 fields
            if len(fields) == 4:
                products      = fields[3].split(',')
                consumer      = fields[2]
                for p in products:
                    product_details = p.split(':')
                    if len(product_details) == 2:
                        product_name     = product_details[0]
                        product_quantity = float(product_details[1])
                        # first we check if the product is in the dict 
                        # if not we add it
                        if product_name not in final_products.keys():
                            final_products[product_name] = dict()
                        # does the consumer already bought this product ?
                        if consumer not in final_products[product_name].keys():
                            final_products[product_name][consumer] = 0.0
                        # finaly we add the quantity bought by the consumer
                        final_products[product_name][consumer] += product_quantity
    # close the file
    fhd.close

print(final_products)

这打印:

{'cereal': {'barakobama': 9.21}, 'potatoes': {'barakobama': 2.67}, 'parsley': {'vladimirputin': 1.33, 'barakobama': 0.76}, 'sugar': {'barakobama': 1.98}, 'crisps': {'barakobama': 1.09}, 'milk': {'vladimirputin': 2.87}, 'bread': {'vladimirputin': 0.66}}

【讨论】:

    猜你喜欢
    • 2013-01-07
    • 1970-01-01
    • 2013-11-21
    • 2015-05-17
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多