简体   繁体   中英

Using dictionary for multiple identical values one key

I would like to achieve the following: Have a dictionary or list with one key 'date' with identical values but different values Example (process of thought)

Data = {}
Data['2017-01-01'] = 123
Data['2017-01-01'] = 321
Data['2017-01-02'] = 123

Expected

{
    '2017-01-01': 123,
    '2017-01-01': 321,
    '2017-01-02': 21
}

Actual result

{
    '2017-01-01': 321,
    '2017-01-02': 21
}

It might be that I am approaching this issue completely incorrect. Let me describe the scenario. I scrap data from an HTML site getting dates and purchase values. There can be multiple values on the same day as in my example above. When I have the data, I would like to loop the data and get Date, sum(value), count

Example

{
   "record":[
      {
         "Date":"2017-01-01",
         "Value":444,
         "Count":2
      }
   ],
   "record":[
      {
         "Date":"2017-01-02",
         "Value":21,
         "Count":1
      }
   ]
}

You could build this dictionary:

adict = {
     '2017-01-01': ['321', '123', '223'],
     '2017-01-02': ['144', '445', '222']
}
adict['2017-01-01'].append('224')

We initialise a list for the keys value and therefore can store multiple values. We can iterate the values at this location more easily that if we had keys of the same name.. IE:

for x in adict['2017-01-01']:
    print x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM