-4

I have a dictionnary with a datetime as key and a numbre as value.

dict = {'08/07/2015 01:15':'3', '08/07/2015 08:15':'5',
 '09/07/2015 07:15':'4', '09/07/2015 10:30':'8'}

I want extract values of each day. For example, on the 09/07/2015 I want this result :

result = {'09/07/2015 07:15': '4', '09/07/2015 10:30': '8'}

or

result = [4, 8]

Thank you for your help.

jony
  • 277
  • 1
  • 3
  • 7
  • possible duplicate of [Filter dict to contain only certain keys?](http://stackoverflow.com/questions/3420122/filter-dict-to-contain-only-certain-keys) – wenzul Aug 03 '15 at 13:50

3 Answers3

2
>>> filter(lambda x: x[0:10] == "09/07/2015", dict)
['09/07/2015 10:30', '09/07/2015 07:15']

Hint: Don't use dict as a variable name. It's already used by python.

And an extensive version:

>>> filtered = {}
>>> for date, value in dict.iteritems():
...     if date.startswith("09/07/2015"):
...        filtered[date] = value
...
>>> filtered
{'09/07/2015 10:30': '8', '09/07/2015 07:15': '4'}
wenzul
  • 3,948
  • 2
  • 21
  • 33
2

If I understand the question, it's not doable without examining all keys in your dict.

dict keys are an unordered set, and because they have no ordering, there is no way to take a "range" of keys in a single operation.

Because you are hashing time into your keys and so there may be any number of keys for 09/07/2015, there is no way to retrieve each of them without looking at all.

Depending on what you are trying to accomplish, you might consider a dict of dicts, where the top dict is by date and inner ones are by time; e.g.

dict = { 
    "08/07/2015": { "01:15":"3" },
    "09/07/2015": { "07:15":"4", "10:30":"8" }
}

or some sort of ordered datatype, like an array (which will cost you in lookup time but require less space).

1

You need to iterate the keys and compare the key value with the desired date.

For example:

>>> sample = {"08/07/2015 01:15":"3", "08/07/2015 01:15":"5", "09/07/2015 07:15":"4", "09/07/2015 10:30":"8"}
>>> filtered = dict((x,y) for (x,y) in sample.items() if x.startswith('09/07/2015'))
>>> filtered
{'09/07/2015 10:30': '8', '09/07/2015 07:15': '4'}
>>> filtered.values()
['8', '4']
MattH
  • 37,273
  • 11
  • 82
  • 84