I am new to python. I was just trying to do some things to get to know python.
What I am now trying to do is merge two arrays of same size. The condition is that if key is a specific value(nk in my case) then value should be appended to the previous key or current key.
below is the code I wrote to do it and its working. I'm sure that I have written a very bad code(beginner :) )
Below code has two arrays. keys and values. What I am trying to do is, if the value in key is nk then that particular element in values array is appended to a list with the key previously obtained.
import json
keys = ["one", "nk", "nk", "two", "nk", "three", "nk", "four", "nk"]
values = ["quick", "brown", "fox", "jumps", "on", "lazy", "dog", "asfdsagfds", "sdfgre"]
mydict = []
key = "head"
val = []
for i in range(0, len(keys)):
if(keys[i] != "nk") :
mydict.append({key:val})
key = ""
val = []
key = keys[i]
val.append(values[i])
else :
val.append(values[i])
if(i == len(keys)-1) :
mydict.append({key:val})
print(json.dumps(mydict, indent=4))
Output :
[
{
"head": []
},
{
"one": [
"quick",
"brown",
"fox"
]
},
{
"two": [
"jumps",
"on"
]
},
{
"three": [
"lazy",
"dog"
]
},
{
"four": [
"asfdsagfds",
"sdfgre"
]
}
]
Now the question is is there any easy way of doing this using any python inbuilt functions?