Python优雅的方式来订购字典数组

时间:2018-09-21 05:41:53

标签: python python-3.x

我有这种格式的数据-

  <template>

            <div class="card">
                <div class="card-header">Subject</div>
                <div class="card-body" >
                    <!-- <ul class="list-group">
                        <li class="list-group-item" :key = "message.id" v-for = "message in messages"> {{ message.subject}}</li>
                    </ul> -->
                    {{messages}}
                </div>
            </div>  

</template>
<script>
export default{
  name: 'subject-component',
    data () {
    return {
     messages:{}
    }   
  },
  mounted () {

  },
    created(){

         axios.get('http://127.0.0.1:8000/subject/get')
          .then(response => {this.messages = response.data})
          .catch((error) => console.log(error));

    }
}
</script>

期望的输出是这个-

[
    {'gstin_code': 'A', 
     'price_effective': 1199.0, 
     'company_id': 489, 
     'month': datetime.datetime(2018, 6, 1, 0, 0), 
     'year': datetime.datetime(2018, 1, 1, 0, 0)
     },
    {'gstin_code': 'B', 
     'price_effective': 1199.0, 
     'company_id': 489, 
     'month': datetime.datetime(2018, 6, 1, 0, 0), 
     'year': datetime.datetime(2018, 1, 1, 0, 0)
     },
    {'gstin_code': 'C', 
     'price_effective': 1199.0, 
     'company_id': 489, 
     'month': datetime.datetime(2018, 6, 1, 0, 0), 
     'year': datetime.datetime(2018, 1, 1, 0, 0)
     }
]

{ "2": { "2018": { "3": { "27AA": 1799 }, "4": { "03AA": 1299, "04AA": 1499, "05AA": 699, "06AA": 599, "07AA": 199, "09AA": 499, "19AA": 599, "23AA": 770, "27AA": 420, "27AA": 499 }, "5": { "03AA": 1399, "27AA": 399, "27AA": 640 } } } }

这些值也都为None,例如company_id,year,month,gst都为None。

可行的解决方案是这个-

{company_id:{year:{month:{gst:price_effective}}}}

有什么优雅的方法可以避免这些if else语句?

1 个答案:

答案 0 :(得分:1)

使用collections.defaultdict,您可以删除密钥是否存在于字典中的检查:

from collections import defaultdict
def nested_dict():
    return defaultdict(nested_dict)

def toNested(data):
    nd = nested_dict()
    for aa in data:    
        nd[aa['company_id']][aa['year'].year][aa['month'].month][aa['gstin_code']] = aa['price_effective']
    return nd

import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint( toNested(data) )

有关更多详细信息和基准,请参见Create Nested Dictionaries in python