I am iterating through the keys of one dictionary, finding the same key in a second dictionary, then trying to produce the first value of the list associated with the key in the second dictionary. When I look directly into the second dictionary it works fine:
Code:
for data in hud_data.get('veh_1'):
print(data[0])
Returns:
17.3245
This is correct. But when I try to run through all of the keys of hud_data by referencing the keys of another dictionary (UAV_data), I get a strange result:
Code:
for a_key in UAV_dict.keys():
# print(a_key)
for data in hud_data.get(a_key):
print(data[0])
break
This should produce the exact same thing. The first key in UAV_dict is 'veh_1', so when the second for loop runs, it should just return the same thing, 17.3245. Instead it returns all of the values for every key:
Return:
17.3245
19.3003
22.2483
29.8077
35.86
Why are all of the values for every key showing up in the output? How should I re-write the code so that it only produces the first outcome?
Your break statement only stops the inner for-loop. The other loop on UAV_dict.keys() is not affected
Related
Let's say I have accessed my dictionary keys using print (hamdict.keys())
Below is a sample output:
I know my dictionary list has a length of 552 elements. I want to randomly select one "key" word from my list and assign it to the variable "starter". I tried to do this with the code below (note: I have a dictionary called hamdict):
random_num = random.randint(0, len(hamdict.keys())-1)
print (random_num)
print (hamdict.keys()[random_num])
I'm able to get a value for random_num so that seems to work. But the second print returns the following error:
How can I fix my code?
my_dictionary.keys() returns a generator-like object, not a list. You can probably get what you want by converting it to a list first
print(list(hamdict.keys())[random_num])
Try this:
random.sample(hamdict.keys(),1)[0]
The sample() function randomly selects a given number of items from a list or iterator. Contrary to the choice function, it supports iterators so you don't need to make a list out of the keys beforehand. The result is a list so you need to get its first item from the output (hence the [0]).
I'm stucked with reading value from my dictionary. My dictionary is like a = {(1,2):(1,2,3,4),(4,5,6,7),...} and my task is to loop value, e.g.,(1,2,3,4) and read value[0] and value[1], in this case, is 1 and 2.
But when I'm not sure if there is a tuple or multiple tuples in value, how can I loop the value and read the first and second value of tuple? I mean, if I use for loop directly towards a, then the result of loop is a value rather than a tuple. How could I deals with this situation? My only thinking is add if statement but I wonder if there is more efficient way. :)
You can loop over the keys in the dictionary and then pull each tuple from the dictionary and loop over those, like so:
for key in dict:
for tuple in dict[key]:
# whatever you want to do with tuple[0] and tuple[1]
I am trying to write from Python into an Excel workbook using XlsxWriter.
I have a dictionary called Pg whose keys are tuples.
for key,value in Pg.iteritems():
for t in range(1,4):
if key==(0,t):
worksheet.write(row,col,value.x)
row += 1
I want to write values of key (0,t) in a column, but the values don't appear in normal order. For example, if my dictionary looks like this:
Pg={(0,1):1,(0,2):2,(0,3):3}
I get in Excel:
1
3
2
Why is this happening when I have strictly determined in the second for loop how I want my values to be written?
I think you realize that when you iterate over a dictionary, you are not guaranteed any specific ordering. The problem you are having is that the way you are trying to force an ordering is flawed.
for key,value in Pg.iteritems():
for t in range(1,4):
if key==(0,t):
# ...
What this does is iterate over each key, value pair first. Then inside this you output if the key matches a certain condition. If you switched the ordering of the for loops, you would get what you wanted, but this method is not efficient at all.
More simply, you can iterate over the sorted dictionary like this:
for key, value in sorted(Pg.iteritems()):
worksheet.write(row, col, value.x)
row += 1
Here is a simple nested dictionary:
wordFrequency = {'bit':{1:3,2:4,3:19,4:0},'red':{1:0,2:0,3:15,4:0},'dog':{1:3,2:0,3:4,4:5}}
I am trying to work out the difference between what these two pieces of code do:
for word, innerDictionary in wordFrequency.iteritems():
for fileNum, appearances in innerDictionary.iteritmes():
and
for fileNum, appearances in wordFrequency.get(word, {}).iteritems():
I know the first allows me to assign the keys and values of the inner dictionary to fileNum and appearances respectively.
However, I am unclear as to if the second piece of code does the same?
The following command :
for fileNum, appearances in wordFrequency.get(word, {}).iteritems():
Will give you only one value (of nested dictionaries) , but if you want it have a same effect like your preceding code ,As the get()'s function first argument must be a key of the dictionary you need to get the keys and put that code in a loop :
for word in wordFrequency.keys() :
for fileNum, appearances in wordFrequency.get(word, {}).iteritems():
How to use set() during iteration? I still have single value.
data = {'mynumber': set()}
example = Example.objects.filter(user=request.user)
for e in example:
data['mynumber'].add(e.mynumber)
print data #{'mynumber': set([15.0])}
try using setdefault:
When your condition satisfy, the following snippet will create an empty set for that number or key, so it will create if its not already exist else it will re-use:
data.setdefault('mynumber', set())
Based on original edit
You're adding to a set mynumber, which can contain only unique values, the results from a django query Example.objects.filter(mynumber=5) which only ever includes items where mynumber is 5... Ergo, you'll only ever end up with an empty set (no query results), or a set containing 5 (1 or more results).
Note
After you've traced through your code to check you're getting the values you're expecting, then you can get rid of the loop and just write your code as:
data = {'mynumber': set(Example.objects.filter(user=request.user).values_list('mynumber'))