-1

I am new and seeking help if someone can. I have been able to create a text file with the output of the defined variable weight. But it writes/prints/posts much more data than I am needing. The followin .py I have is below.

#!/usr/bin/python
import myfitnesspal
import requests
import lxml
import measurement
import six
import mock
import datetime

client = myfitnesspal.Client('username', 'password')

weight = client.get_measurements('Weight')
print weight

file = open("ChrisFitPal.txt", "w") 
file.write(repr(weight) + '\n' )
file.close() 

The output I get is the following in a text file But I only want it to show a snippet of the text

This is what it shows in a text file

OrderedDict([(datetime.date(2019, 1, 2), 174.4), (datetime.date(2018, 12, 26), 175.6), (datetime.date(2018, 12, 21), 175.1), (datetime.date(2018, 12, 13), 173.2), (datetime.date(2018, 12, 7), 175.0)])

I just want the text file to show the number that is in bold and italics and nothing else. So the output would be just

174.4

is this possible?

  • 1
    You mean you want the most recent measurement? So what have you tried? – jonrsharpe Jan 03 '19 at 22:38
  • Print weight displays exactly "OrderedDict([(datetime.date(2019, 1, 2), 174.4), (datetime.date(2018, 12, 26), 175.6), (datetime.date(2018, 12, 21), 175.1), (datetime.date(2018, 12, 13), 173.2), (datetime.date(2018, 12, 7), 175.0)])" – Christoph Bryan Roesch Jan 04 '19 at 01:25

2 Answers2

0

You can change:

file.write(repr(weight) + '\n' )

To:

file.write(a[next(iter(a))] + '\n' )

Where:

a = OrderedDict([(datetime.date(2019, 1, 2), 174.4), (datetime.date(2018, 12, 26), 175.6), (datetime.date(2018, 12, 21), 175.1), (datetime.date(2018, 12, 13), 173.2), (datetime.date(2018, 12, 7), 175.0)])

This gives you an iterator object of the OrderedDict values. You call next to advance the iterator by 1, giving you the key of the first item. You then use that key to access the value stored against that. There are a few options given by Raymond Hettinger in this answer

roganjosh
  • 12,594
  • 4
  • 29
  • 46
  • It isn't a single value, is it? It's a series of date-weight (presumably in pounds) values. – John Gordon Jan 03 '19 at 22:40
  • 1
    @JohnGordon the "bold, italics" literally is a single value so I've taken it literally. They seem to be pretty clear on a single output? – roganjosh Jan 03 '19 at 22:41
  • @JohnGordon oops, ok, we were coming from different angles. I didn't intend to imply the `OrderedDict` only contained one value, only that I was unsure why you'd have such a structure and only want the first value. Removed that statement. – roganjosh Jan 03 '19 at 22:45
0

Looks like you are returning a dict from client.get_measurements('Weight'), so you can cast it to a list and index in to get only a certain item

d={'a':1,'b':2,'c':3}

list(d.items())
[('a', 1), ('b', 2), ('c', 3)]

list(d.items())[0]
('a', 1)

list(d.items())[0][1]
1
G. Anderson
  • 5,815
  • 2
  • 14
  • 21