Python read tuples from dictionary - python

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]

Related

summing dict value of list to single integer

I am trying to do something pretty simple but cant seem to get it. I have a dictionary where the value is a list. I am trying to just sum the list and assign the value back to the same key as an int. Using the code below the first line doesn't do anything, the second as it says puts the value back but in a list. All other things ive tried has given me an error can only assign iterable. As far as i know iterables are anything that can be iterated on such as list and not int. Why can I only use iterable and how can i fix this issue ? The dict im using is here (https://gist.github.com/ishikawa-rei/53c100449605e370ef66f1c06f15b62e)
for i in dict.values():
i = sum(i)
#i[:] = [sum(i) / 3600] # puts answer into dict but as a list
You can use simple dictionary comprehension if your dict values are all lists
{k:sum(v) for k, v in dict.items()}
for i in dikt.keys():
dickt[i] = sum(dict[i]))
btw, dict is a type. best not to use it as a variable name

How to force dictionary elements to be written in order?

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

Functioning of append in dictionary?

Please explain the use of append function in the following example:
Example 1:
new = {}
for (key, value) in data:
if key in new:
new[key].append( value )
else:
new[key] = [value]
and in example 2:
new = {}
for (key, value) in data:
group = new.setdefault(key, [])
group.append( value )
new is a dictionary, but the dictionary’s value are lists, which have the list.append() method.
In the loop, the dictionary is being filled with the values from data. Apparently, it is possible that there are multiple values for a single key. So in order to save that within a dictionary, the dictionary needs to be able to store multiple values for a key; so a list is being used which then holds all the values.
The two examples show two different ways of making sure that the dictionary value is a list when the key is new.
The first example explicitly checks if the key is already in the dictionary using key in new. If that’s the case, you can just append to the already existing list. Otherwise, you need to add a new list to the dictionary.
The second example uses dict.setdefault which sets a value if the key does not exist yet. So this is a special way of making sure that there’s always a list you can append the value to.

How to update dictionary and return update key/value pairs

I am writing a function add_to_dict(d, key_value_pairs) which adds each given key/value pair to the given dictionary. The argument key_value_pairs will be a list of tuples in the form (key, value).
The function should return a list of all of the key/value pairs which have changed (with their original values).
def add_to_dict(d,key_value_pairs):
key_value_pairs=()
thelist=[]
thelist.append(list(d))
for key, value in key_value_pairs:
d[value]=key
thelist.append(list(key_value_pairs))
return thelist
What I got here seems completely not right and I have no clue at the moment.
From what I understand, you want to add a list of key/value tuples to a dictionary. The function will return all of the key/value pairs that were changed. I commented the problems I found in your code.
def add_to_dict(d,key_value_pairs):
key_value_pairs=() #This changes your list of key/value tuples into an empty tuple, which you probably don't want
thelist=[]
thelist.append(list(d)) #This appends all of the keys in d to thelist, but not the values
for key, value in key_value_pairs:
d[value]=key #You switched the keys and values
thelist.append(list(key_value_pairs)) #This is already a list, so list() is unnecessary
return thelist
I would suggest simply returning key_value_pairs as it already contains all of the keys and values that were modified. Let me know if you need more detail on how to fix the problems, but first try and figure it out yourself.

Assigning multiple values to a key?

I have a dictionary that needs its values to be 2D lists. I am having trouble adding these second values to a key. I have two lists, the first a list of values then a list of keys that is composed of additional lists.
So far I have this code:
for i in range(len(keyList)):
if keyList[i] in theInventory:
value = theInventory[keyList[i]]
value.append(valueList[i])
theInventory[keyList[i]] = value
else:
theInventory[keyList[i]] = valueList[i]
The problem is that the output has a list of entries for the first added to the list then it has the lists I am looking to add to my dictionary.
Like so:
[value, value, value, [list], [list]]
How do I make the first entry be entered into the dictionary as its own list?
Use extra [] around valueList[i]:
theInventory[keyList[i]] = [valueList[i]]
You can simplify your code as follows. The append() method mutates the list, so there is no need to assign the result of the append back the theInventory. Further there is no need to use value at all, instead you can just directly append to the item in the dictionary.
for i in range(len(keyList)):
if keyList[i] in theInventory:
theInventory[keyList[i]].append(valueList[i])
else:
theInventory[keyList[i]] = [valueList[i]]

Categories

Resources