1

I am currently storing values provided by an API response that returns XML, certain nodes come back with 'false' or 'true' I am capturing these values as a string type.

XML Code:

<hidden>false</hidden>
<ssl>true</ssl>
<current_payout>true</current_payout>

I want to parse through these values and if I find a match I would like to change 'true' to 'on' and false to 'off' depending on the variable that matches.

I am only able to accomplish this with one variable, my goal is to clean up my code and find a more efficient way, any advice is appreciated.

Here is my block of code:

import requests
import json
import csv
from bs4 import BeautifulSoup



for data in csv_reader:

req = requests.get(url, params=params)
response = BeautifulSoup(req.text, 'lxml')

hidden = response.find('hidden').string
ssl = response.find('ssl').string
currentPayout = response.find('current_payout').string

if hidden == 'true':
    hidden = 'on'
if hidden 'false':
    hidden = 'off'

if ssl == 'true':
    ssl = 'on'
if ssl = 'false':
    ssl = 'off'

if currentPayout == 'true':
    currentPayout = 'on'
if currentPayout = 'false':
    currentPayout = 'off'

Question: How do I take my 3 if statements and consolidate my code?

2
  • 2
    This should probably be moved to codereview.stackexchange.com Commented Apr 16, 2019 at 23:06
  • 2
    Please fix your indentation. Commented Apr 16, 2019 at 23:06

2 Answers 2

2

How about this:

response_map = {'true': 'on', 'false': 'off'}
find_terms = {'hidden', 'ssl', 'current_payout'}

result = {find_term: response_map[response.find(find_term)] for find_term in find_terms}

result['hidden'], result['ssl'] and result['current_payout'] will have the values you want.

Sign up to request clarification or add additional context in comments.

Comments

1

gmds has a good answer, however if you want to keep your code out of a loop you could use ternary assignment to streamline your existing code a bit.

ssl = 'on' if ssl == 'true' else 'off'
hidden = 'on' if hidden == 'true' else 'off'
currentPayout = 'on' if currentPayout == 'true' else 'off'

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.