Creating dictionary using python from javascript var data [duplicate] - javascript

This question already has answers here:
Convert [key1,val1,key2,val2] to a dict?
(12 answers)
Make dictionary from list with python [duplicate]
(5 answers)
Convert list into a dictionary [duplicate]
(4 answers)
Closed 4 years ago.
trying to figure out how to do this and have yet to find a good solution. I pulled this data out of an XML response. It was in a var tag. Now what I would like to do is create a dictionary out of it. The domain.com should be paired with the number right listed behind it.
This is the data:
[
'cb131.domain1.com', '147827',
'cb143.domain2.com', '147825',
'cb175.domain1.com', '147454',
'cb190.domain.com', '146210',
'cb201.domain.com', '146208',
'cb219.domain.com', '146042',
'cb225.domain.com', '146282',
'cb900.domain.com', '148461',
'cb901.domain.com', '148493',
'cb902.domain.com', '148495',
'cb903.domain.com', '148497',
'cb904.domain.com','148499',
'cb905.domain.com', '148501',
'cb906.domain.com', '148503',
'cb907.domain.com', '148505',
'cb908.domain.com', '148507',
'cb909.domain.com', '148509'
]
So for example cb131.domain1.com should be paired with 147827, cb143.domain2.com paired with 147825 and so on.
Drawing a blank on a good quick solution on how to do this. Hopefully someone can help.
Thanks!
Edited with answer I choose below:
I choose this answer and also to help anyone else I add a nice way to print out the results (data is the string I obtained):
import ast
i = iter(ast.literal_eval(data))
dic = dict(zip(i, i))
for key , value in dic.items():
print(key, " :: ", value)

This should do it. Assuming the list is saved to a variable l:
keys = l[::2]
vals = l[1::2]
dic = dict(zip(keys, vals))

You can create an iterator from the list after using ast.literal_eval to parse it from the input text, zip the iterator with itself, and pass the generated sequence of tuples to the dict constructor:
import ast
i = iter(ast.literal_eval(data))
dict(zip(i, i))

Assuming you have the above in a python array called data, you can do:
new_data = []
for i in range(0, len(data), 2):
new_data.append((data[i], data[i+1]))
Now new_data would be a list of tuples. You could certainly create a better data structure to hold these pairs if you want.

I do not yet know Python that I can write a snippet, but:
initialize an empty dictionary in Python
create a for loop counting index from 0 to length of your array in steps of two.
inside add a dictionary entry with key of value at index and value at index + 1
perhaps check for duplicates
Does this answer help you?
This is Python - quickly google'd:
dictionary = { }
for idx in range(0, len(data), 2)
dictionary[data[idx]] = data[idx + 1]

Related

Is there a way to add each value to the first one in the for loop in JS? [duplicate]

This question already has answers here:
Easy way to turn JavaScript array into comma-separated list?
(22 answers)
Closed 2 years ago.
I have 4 different values, when looping through an array. Is it possible to add the values together like you would in Java's StringBuilder append?
I want something like this when doing a console.log():
28.0334307,-25.872523799999996, 28.031527552564445,-25.87632233243363
Now I am just getting it one for one like this when doing a console.log():
28.0334307
-25.872523799999996
28.031527552564445
-25.87632233243363
Here is my code:
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
for(var item in coordinates)
{
console.log(item);
}
you can get a string in-line separated by a comma with join() method, try this:
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
console.log(coordinates.join(', '));
Try this:
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
console.log(coordinates.join(' '));
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
console.log(coordinates.join(' '));
The browser consoles displays an array like that in to be more readable. It's not an actual structural representation of how an array is. What you want is basically a string created by joining the elements of the array.
Array.join method can be used for this:
coordinates.join("'")
Use JavaScript array join() method to display values separated by comma.
The join() method returns the array as a string.
The elements will be separated by a specified separator. The default separator is a comma (,).

Javascript long integer from server is not accurate [duplicate]

This question already has answers here:
Javascript - convert an EXTRA LARGE Number to string in JSON before the default parsing
(4 answers)
Closed 4 years ago.
I've got an API which I make a get request to fetch data. When i try to save the Id, I see Javascript round the last digit of it and it makes my program to break!
I see THIS QUESTION but how can I save each Id as string?
I'm using a global array to store the selected items' data so, anyway to save one attribute of a JSON in string?
I'm going to have (for example) 3 items and make another get request for each Id:
axios.get(`http://api.nemov.org/api/v1/Market/Symbol/${this.props.ID}`)
One of those Ids, is: 9481703061634967 but JS convert that to 9481703061634968 so the get request is broken!
Any solution?
See my solution on this question:
Transform the response to string, then apply a repalce with a regex to
convert Id field to string type:
const axios = require("axios");
axios.get(url, {transformResponse: [data => data]}).then((response) => {
let parsed = JSON.parse(response.data.replace(/"Id":(\d+),/g, '"Id":"$1",'))
console.log(parsed)
});
Use this:
let strId = this.props.ID.toString();
axios.get(`http://api.nemov.org/api/v1/Market/Symbol/${strId}`)

Counting a particular word in a string using Zapier code

I use Zapier to automate many of our business functions, which is great, but I got stuck trying to count the number of arrays or, if you like, a particular word pattern that comes from a string. I can tidy up the string with Zapier formatter, but cannot figure out how to carry out a count.
Here is an example of a tidied string where " have been removed:
[{Name:Jon,Surname:Smith},{Name:David,Surname:Michael},{Name:Sam,Surname:Fields},{Name:Katy,Surname:Milnes}]
In this instance I would want the count on say "Name" to return 4.
I have looked at different code examples for counting words but cannot execute them correctly in the code action of Zapier. This is probably really straight forward but I do not come from a coding background so a simple Java (or Python) script to drop into the Zapier code action or some pointers on how to solve this would be greatly appreciated.
Thanks
What are you really trying to achieve by trying to count the word?
Do you just want to know the number of objects the array contains? If that is the case something like this would work. Assuming that the array is in your inputData for the code step.
var data = JSON.stringify([{'Name':'Jon', 'Surname':'Smith'},{'Name':'David','Surname':'Michael'},{'Name':'Sam','Surname':'Fields'},{'Name':'Katy','Surname':'Milnes'}]);
var inputData = {objArr: data};
// Do not insert the above lines in your code step.
// Set the objArr to your array in the inputData step.
var parsedObjArr = JSON.parse(inputData.objArr);
// Skip the above step if the array is not in the inputData object.
var arrLen = parsedObjArr.length
console.log('Array Length: ', arrLen);
// The line below outputs data from the code step.
output = {arrLen}
Also note, you do not need to remove the quotes from the JSON string.
If the array is not in the inputData of the code step, you can just directly use the length method on the array.
Well in Python you can convert the json string into dictionary with key as the name. Length of dictionary is what you are looking for. Here is the example:
import json
from collections import defaultdict
d=defaultdict(list)
x=json.dumps([{'Name':'Jon', 'Surname':'Smith'},{'Name':'David','Surname':'Michael'},{'Name':'Sam','Surname':'Fields'},{'Name':'Katy','Surname':'Milnes'}])
json_string=json.loads(x)
for obj in json_string:
if(obj['Name'] in d):
d[obj['Name']].append([obj['Name']+' '+obj['Surname']])
else:
d[obj['Name']]=[obj['Name']+' '+obj['Surname']]
print(len(d))

Get data from JS array of objects [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
Probably very easy question, but I couldn't find solution.
How to get data from this object?
That how it looks in consolo.log()
UPDATE:
Thank you for you answers.
That what I used before and it worked, but when I try on this array it returns error.
console.log(array[1].data);
Output picture
UPDATE2:
So I tried to make it a text, but I couldn't.
console.log(tempArray);
console.log("String: " + tempArray.toString());
console.log("Stringify: " + JSON.stringify(tempArray));
Here is output:
Stringify attempt result
Maybe there is something wrong with how I create this array.
let tempArray = [];
And in the loop
tempArray.push({"id": id, "data": data.routes[0].geometry});
Thank you,
Dmitry
That's an array of objects, so you would get elements from it like so:
console.log(obj[i].data)
Where i is the element (numbered 0 through 2) that you want to access.

Basic JQuery API call - how to specify part of the response? [duplicate]

This question already has answers here:
parsing out ajax json results
(3 answers)
Closed 9 years ago.
I'm very, very new to APIs (an hour in), and I'm just trying to get to the point where I can output a single part of an API response into console.log - and work from there.
Here's the working code which grabs all the data (for example, to display the last price in Bitcoin:
$.ajax({
url: "https://api.bitcoinaverage.com/ticker/all",
dataType: 'json',
success: function(results){
var gpbvalue = results;
console.log(gpbvalue);
}
});
And here's the data itself: https://api.bitcoinaverage.com/ticker/all
How would I specify just the 'last' value under GPB, rather than outputting the entire set of data?
Thank you so much for any help!
This is what you want.
console.log(results.GBP.last);
var gbpvalue = results.GBP.last;
or results["GBP"]["last"], both are equivalent.
The response is a JSON where the first key is a country code and the last value is a key under that. If you wanted to pick a specific last value you could access it like this:
console.log(results['AUD']['last']);
Or if you wanted all last keys you could do this:
for(key in results) {
console.log(results[key]['last']);
}
You can use dot notation but one of the keys 24h_avg is an invalid variable name (vars can't start with numbers) so named index notation is a better habit to get into.

Categories