如何在字典中为键中的键添加值?蟒蛇

时间:2016-07-26 11:37:54

标签: python list file python-3.x dictionary

所以我有一个csv文件,我必须从中找到按类别分组的所有产品的平均价格。我设法将文件中的所有行放入列表中。 现在我试着这个:

FILE_NAME = 'catalog_sample.csv'
full_catalog = []

with open(FILE_NAME, encoding='utf-8') as file:
    for line in file:            
        one_record = line.split(',')
        full_catalog.append(one_record)

category_dict = {}
prices = []

for i in full_catalog:
    if str(i[-2]) not in category_dict:
        category_name = str(i[-2])
        category_dict[category_name] = float(i[-1])
    else:
        prices.append(float(i[-1]))

到目前为止,我收到了一个字典,其中包含文件中的所有类别作为键,但该值是文件中第一次出现该键的价格:

'Men': 163.99
'Women': 543.99

似乎"否则"因为我期待(为键添加值)不起作用。有什么建议?谢谢!

1 个答案:

答案 0 :(得分:0)

我建议您在浏览文件时创建字典,而不是将它们添加到列表中,然后通过它来构建字典。

class WizardForm extends Component {
  constructor(props) {
    super(props)
    this.nextPage = this.nextPage.bind(this)
    this.previousPage = this.previousPage.bind(this)
    this.state = {
      page: 1
    }
  }

  nextPage() {
    this.setState({ page: this.state.page + 1 })
  }

  previousPage() {
    this.setState({ page: this.state.page - 1 })
  }

  render() {
    const { onSubmit } = this.props
    const { page } = this.state
    return (<div>
        {page === 1 && <WizardFormFirstPage onSubmit={this.nextPage}/>}
        {page === 2 && <WizardFormSecondPage previousPage={this.previousPage} onSubmit={this.nextPage}/>}
        {page === 3 && <WizardFormThirdPage previousPage={this.previousPage} onSubmit={onSubmit}/>}
      </div>
    )
  }
}

编辑:已修复以匹配提供的行格式。 如果您仍需要整个列表

,则已包含category_dict = {} full_catalog = [] with open(FILE_NAME, encoding='utf-8') as file: for line in file: item = line.split(',') # Unpack the last 2 items from list category = item[-2].strip() price = float(item[-1]) # Try get the list of prices for the category # If there is no key matching category in dict # Then return an empty list prices = category_dict.get(category, []) # Append the price to the list prices.append(price) # Set the list as the value for the category # If there was no key then a key is created # The value is the list with the new price category_dict[category] = prices full_catalog.append(item)