Python create nested dict in for loop [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to created a nested dictionary but I have a problem inside the for loop, at least is what I'm thinking.
I do several requests based on args passed but when I try to add values to the nested dict created before it just adds the last arg passed.
I'll show the code and the output.
def api_metrics():
my_list = []
my_dict_1 = {}
number = len(my_metrics)
metricz = range(number)
for indice in metricz:
my_dict_1[indice] = {}
for metric in my_metrics:
urlnotoken = ""
urlnotoken = urlnotoken.replace(" ","%20")
preurl = urlnotoken + "&dateToken="+expirationDate
msg = preurl + apikey
token = calcMd5(msg)
finalurl = "http://"+host+preurl+"&token="+token
data_get = requests.get(finalurl, headers=app_headers)
json_data = json.loads(data_get.text)
metrics_path = json_data['data'][0]['metrics'][0]
metric_name = metrics_path['label']
metric_value = metrics_path['values'][0]['data'][0][1]
metric_unit = metrics_path['magnitudes']['y']
my_list.append(metric_name)
my_list.append(metric_value)
my_list.append(metric_unit)
number = len(my_metrics)
metricz = range(number)
my_values = metric
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
return(my_dict_1)
And the output
{0: 'avgRenditionSwitchTime', 1: 'avgRenditionSwitchTime', 2: 'avgRenditionSwitchTime', 3: 'avgRenditionSwitchTime', 4: 'avgRenditionSwitchTime'}"
This should output the different args passed. I have moved the code inside and outside the loop, I've read lots of posts but I need further help!
Cheers.

In here:
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
You are assigning the value of metric to all your dict (my_dict_1) items. Reason why 'it just adds the last arg passed'.
Without cleaning up your code, here's the patch to fix your issue:
for i, metric in enumerate(my_metrics):
...
my_dict_1[i] = metric

Related

How would I add the results of a 'for' loop into a dictionary? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I am required to take 52 random outputs of cards. I got that in a for loop. The problem is, I need to save that output inside a variable.`
import random
r=random.randint(0, 9)
cards={'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2={}
for i in range(52):
global res
res = key, val = random.choice(list(cards.items()))
print("Your deck contains " + str(res))
cards2.update(i) # All output should go in here
I tried using cards2.update, but it didn't work.
I also tried using cards2.(keys).
I just need to create 52 random samples and store them as dictionary value pairs.
First remove the double assignment (res = key, val). And I don't see any point in using a global variable here. Just do _dict[key] = value as shown below, and it will work fine. Also remember that you can’t get all 52 random cards, because if the key exists then the value will be replaced.
import random
r = random.randint(0, 9)
cards = {'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2 = {}
for i in range(52):
key, val = random.choice(list(cards.items()))
cards2[key] = val
print(cards2)

Linking elements of a list as a tree [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a python list that looks like this for example :
[Product(parent=tube,child=spokes), Product(parent=bicycle, child=wheel), Product(parent=wheel,child=tube)]
Where Product is a python class with two members parent and child.
The Products could appear in any order in the list.
What would be the most efficient one liner to achieve the following :
Given an input spokes for example , return the `root of the tree` , bicycle in this case.
What have i tried so far : inefficient for loops that does not give the right results when the Product does not appear in the same order each time.
You do not write how strong assumption you can apply to data (if it is always proper tree). So my code check some conditions to not stick in infinity loop.
def find_root(pr_list, child):
if len(pr_list) == 0:
return None
child_translate_dict = {x.child: x for x in pr_list}
potential_root = child
count = 0
while count < len(pr_list):
if potential_root not in child_translate_dict:
return potential_root
else:
potential_root = child_translate_dict[potential_root].parent
count += 1
return None
and shorter version
def find_root(pr_list, child):
child_translate_dict = {x.child: x for x in pr_list}
while child in child_translate_dict:
child = child_translate_dict[potential_root].parent
return child
Here is a pseudo code for your problem :
def recursiveRootFinder(child,theList):
for(i in theList):
if (i.child==child):
child=recursiveRootFinder(i.parent,theList)
return child
You can use lambda definition to implement it in one line like that :
lambda child,theList: recursiveRootFinder(i.parent,theList) for i in list if i.child==child if [1 for i in list if i.child==child]!=[] else child

Error adding list in loop condition in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
while dir_loop_water < water_lenth:
ds_water = gdal.Open('path'+ dirlist_water[dir_loop_water] , gdal.GA_ReadOnly)
numer_of_band_water = str(ds_water.RasterCount)
if numer_of_band_water == '3':
print('water condition matched')
rb_water = ds_water.GetRasterBand(1)
band1_water_tmp = rb_water.ReadAsArray()
band1_water = band1_water_tmp.tolist()
rb2_water = ds_water.GetRasterBand(2)
band2_water_tmp = rb2_water.ReadAsArray()
band2_water = band2_water_tmp.tolist()
rb3_water = ds_water.GetRasterBand(3)
band3_water_tmp = rb3_water.ReadAsArray()
band3_water = band3_water_tmp.tolist()
[cols_water,rows_water] = band1_water_tmp.shape
loop_water_cols = 0
while loop_water_cols < cols_water:
loop_water_rows = 0
while loop_water_rows < rows_water:
dataset.append([band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0])
loop_water_rows = loop_water_rows +1
del dataset[0]
with open('path/dataset.csv', 'a') as f:
writer = csv.writer(f)
writer.writerows(dataset)
f.close()
dataset= [None]
loop_water_cols = loop_water_cols +1
dir_loop_water= dir_loop_water+1
With the above code, I want to add lists with length 4 to dataset.
but i print dataset's value(print(dataset[number])), it print like this.
[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0]
[0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]
In my opinion of above code, I add one list with four values.
However, the result is a combination of two lists with four values.
I could not find where the list would be merged.
Thanks for letting me know how to add only one list with 4 values at a time.
Your dataset.append() method is appending the entire list into your list (making a list of lists).
To append each item of the new list into the dataset (If I'm understanding you correctly) use += like so:
dataset += [band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0]
this will result in a list like so:
[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0, 0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]

Implementing treeset data structure store and read in VBA / Python/ Shell [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a text file like this
LEVEL=3
LEVEL1=CLASS7
LEVEL2=ROLLNO1
LEVEL3=MALE
JOHN,12
LEVEL2=ROLLNO2
LEVEL3=FEMALE
JULIA,11
We need to read this file and need output like
CLASS7|ROLLNO1|MALE|JOHN|12
CLASS7|ROLLNO2|FEMALE|JULIA|11
1st LELVEL=3 means maximum LEVEL present in the file.
Here LEVEL 1 is common, but in actual data sometimes LEVEL 1 and 3
can be common when maximum LEVEL is say 7.Basically there is no clear
pre-defined pattern.
I have solved it in VBA using normal array structure but when file becomes
very big and maximum LEVEL becomes more( like more than 10)
it becomes slow.
Then I tried to read more things and came to know using
treeset data structure and iterator kind of things it works fast.
But this things possible in Java.
How we can do it in VBA ?
If possible in shell or python that is also ok.
here is a little python approache, but very specific on you string formating, with "text.txt" containing your text:
f = open( "text.txt", 'r' )
text = f.readlines()
f.close()
d = { }
for line in text :
pair = line.split( '=' )
if len( pair ) == 2 : # save Levels as pairs in dict
d[pair[0].strip()] = pair[1].strip()
else : line without level means time for output
out = [] # gather the values in here
try :
for i in range( 1, int( d['LEVEL'] ) + 1 ) : # number of levels (1-based)
out.append( d['LEVEL' + str( i )] ) # add every level
except KeyError :
pass
out += line.split( ',' ) # add current line
out_as_string = '|'.join( out ) # convert to string with "|"
print( out_as_string )
outputs:
CLASS7|ROLLNO1|MALE|JOHN|12
CLASS7|ROLLNO2|FEMALE|JULIA|11

Python: How to print my simple poem [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to know how I could print out sentences using my triplet poem program.
My program randomly picks a list of nouns to use.
My program:
import random
def nouns():
nounPersons = ["cow","crowd","hound","clown"];
nounPlace = ["town","pound","battleground","playground"];
rhymes = ["crowned","round","gowned","found","drowned"];
nounPersons2 = ["dog","frog","hog"];
nounPlace2 = ["fog","Prague","smog"];
rhymes2 = ["log","eggnog","hotdog"];
nounList1 = [nounPersons,nounPlace,rhymes]
nounList2 = [nounPersons2,nounPlace2,rhymes2]
nounsList = [nounList1, nounList2]
randomPick = random.choice(nounsList)
return(randomPick)
verbs = ["walked","ran","rolled","biked","crawled"];
nouns()
For example, I could have "The cow walked to the town. But then it was drowned." And just replace the nouns/rhyme(cow, town,drowned) and verb(walked) with my randomizer.
Would I use random.randint in some way?
I just basically need a general print statement like the example I showed using my randomizer to randomly pick between the nouns/rhymes.
As usual (for me), there may be a more Pythonic approach, but to get what you have working, I did three things:
assigned your call to the nouns() function to 'chosen_list' variable. That way the returned 'randomPick' gets used.
built in a selection step to get individual words from the lists in 'chosen_list' and your verb list
added a final print statement with formatting to assemble the words in to a sentence
the code:
import random
def nouns():
nounPersons = ["cow","crowd","hound","clown"];
nounPlace = ["town","pound","battleground","playground"];
rhymes = ["crowned","round","gowned","found","drowned"];
nounPersons2 = ["dog","frog","hog"];
nounPlace2 = ["fog","Prague","smog"];
rhymes2 = ["log","eggnog","hotdog"];
nounList1 = [nounPersons,nounPlace,rhymes]
nounList2 = [nounPersons2,nounPlace2,rhymes2]
nounsList = [nounList1, nounList2]
randomPick = random.choice(nounsList)
return randomPick
verbs = ["walked","ran","rolled","biked","crawled"]
# this is change 1.
chosen_list = nouns()
# select single words from lists - this is change 2.
noun_subj = random.choice(chosen_list[0])
noun_obj = random.choice(chosen_list[1])
rhyme_word = random.choice(chosen_list[2])
verb_word = random.choice(verbs)
# insert words in to text line - this is change 3.
print ("The {} {} to the {}. But then it was {}.".format(noun_subj, verb_word, noun_obj, rhyme_word))

Categories

Resources