J. Doe
J. Doe

Reputation: 1549

Tying multiple dictionary entries to one key

I have some code that I am writing, and it is trying to imitate what an API call does. However there are multiple entries that can be put in the API call that have the same keys. For example, if you look at my call to the method, there are multiple names[] that are passed as part of the API call.

names[]": ["System/CPU/User/percent", "System/CPU/System/percent"]

Here is the code that have -

def new_relic_api(api_key, query_function, datapoints):
   temp = {}

   if (datapoints != None):
      for k, v in datapoints.iteritems():
          if isinstance(v, list):
              for s in v:
                  print (k)
                  print s
                  temp[k] = s

          else:
              print k
              print v
              temp[k] = v

   r = requests.get(url, headers=headers, data=temp)

d = {"names[]": ["System/CPU/User/percent", "System/CPU/System/percent"], "values[]": "average_value", 'from': '2016-11-30T18:31:00+00:00', 'to': '2016-11-30T19:01:00+00:00', 'summarize': 'true'}
new_relic_api("${api_key}", "/servers/{server_id}/metrics/data.json", d)

However, the actual dictionary is only printing out the second names[] value inside of the requests call. How can I fix this?

Thanks

Upvotes: 0

Views: 50

Answers (1)

Gennady Kandaurov
Gennady Kandaurov

Reputation: 1964

That's because you write into dictionary temp in line temp[k] = s different values from "names[]" but with the same key:

items = {}
k = "names[]"
for s in ["System/CPU/User/percent", "System/CPU/System/percent"]:
    items[k] = s
# items == {"name[]": "System/CPU/System/percent"}

It means that last value of s rewrites items[k] and items will always keep only one (last) value of names[].

Another thing is it's better to check if a value equals None with is operator:

if value is None: pass
if value is not None: pass

To pass both names[] values simultaneously you don't need to split its values, use requests.get and pass names[] as a list:

temp = {"names[]": ["System/CPU/User/percent", "System/CPU/System/percent"]}
r = requests.get(url, headers=headers, data=temp)

It will be requested as smth similar to:

url?names[]=System/CPU/User/percent&names[]=System/CPU/System/percent

Upvotes: 1

Related Questions