0

I have this array :

[
  {u'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41), u'rawValue': -200.0, u'data_type': 's'}, 
  {u'createdAt': datetime.datetime(2018, 8, 1, 11, 58), u'rawValue': -200.0, u'data_type': 's'}, 
  {u'createdAt': datetime.datetime(2018, 8, 1, 11, 56, 51), u'rawValue': -200.0, u'data_type': 'm'}
 ]

I want to get only one sub array that correspond on 2 conditions :

1 : createdAt is bigger

2 : data_type = s

Is possible to do this thing by using some libraries ?

I trying like this :

dataToReturn = []

    for data in datas:
        if date_type in data['data_type']:
            dataToReturn.append(data['data_type'])
    return dataToReturn

But seems is not the better idea.

Expected output :

['createdAt' : datetime.datetime(2018, 8, 1, 12, 3, 41), 'rawValue' : -200.0]
2
  • Can you post expected output? Commented Aug 1, 2018 at 12:10
  • I edited the question @Rakesh Commented Aug 1, 2018 at 12:12

2 Answers 2

1
import datetime

d = [
  {u'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41), u'rawValue': -200.0, u'data_type': 's'}, 
  {u'createdAt': datetime.datetime(2018, 8, 1, 11, 58), u'rawValue': -200.0, u'data_type': 's'}, 
  {u'createdAt': datetime.datetime(2018, 8, 1, 11, 56, 51), u'rawValue': -200.0, u'data_type': 'm'}
 ]

value = [i for i in d if i["data_type"] == "s"]
res = sorted(value, key=lambda x: x["createdAt"], reverse=True)
print(res[0])
print(len(value))

Output:

{u'data_type': 's', u'rawValue': -200.0, u'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41)}
2
  • [i for i in d if i["data_type"] == "s"] to get dict with data_type == "s"
  • Use sorted to sort by datetime and then use index
Sign up to request clarification or add additional context in comments.

2 Comments

exist a possibility to get the number of items in array, for example I want the number of sub arrays with data_type = "s", in my case, the count = 2 ?
Updated snippet
0

You can use max to find the sub array that has biggest createdAt time

>>> import datetime
>>> lst = [{u'data_type': 's', u'rawValue': -200.0, u'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41)}, {u'data_type': 's', u'rawValue': -200.0, u'createdAt': datetime.datetime(2018, 8, 1, 11, 58)}, {u'data_type': 'm', u'rawValue': -200.0, u'createdAt': datetime.datetime(2018, 8, 1, 11, 56, 51)}]
>>> {str(k):v for k,v in max(filter(lambda x: x['data_type'] == 's', lst), key=lambda x: x['createdAt']).items() if str(k) in ['createdAt', 'rawValue']}
{'rawValue': -200.0, 'createdAt': datetime.datetime(2018, 8, 1, 12, 3, 41)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.