I get this error message:
TypeError: list indices must be integers, not list
Using this code:
def invert_networks_dict(person_to_networks):
"""
(dict of {str: list of str}) -> dict of {str: list of str})
"""
networks_to_person = []
for person in person_to_networks:
networks = person_to_networks[person]
networks_to_person[networks] = person
if not (networks in networks_to_person):
networks_to_person[networks] = person
else:
networks_to_person[networks].append[person]
How can I fix it?
You should have initialized networks_to_person as dictionary:
networks_to_person = {}
networks_to_person = []
This assigns networks_to_person to a list. However, you want it to be a dict:
networks_to_person = dict() # <--
You can also use {} (empty dict literal), but I prefer dict() because it makes your intent more explicit.
#glglgl brought up a good point in the comments (which I'll restate here for completeness).
networks_to_person[networks].append[person]
You want to call append here, not index it. Therefore, you want:
networks_to_person[networks].append(person)
Lastly, note that you can't have lists as keys to a dictionary. You can convert them to tuples (which can be keys) instead using tuple().
if you want to 'reverse' dictionary d (swap keys and values), with values being list of strings you can:
dict((tuple(val), key) for key, val in d.items())
However, you can do this only if d.values are unique, as keys in new dictionary must be unique.
Explanation:
dict() is a built-in that creates dictionary from sequence of pairs (key, value). As with every dictionary, key must be hashable.
Because we want to make values of d new keys, we need to transform them to something hashable - in this case this will be tuple. We can create it from any sequence, including lists that are values of d, with another builtin: tuple().
So what we need are pairs of keys in values from d. We can get them using d.items(). We can make this in easy way using list comprehension, additionally wrapping val in tuple, to make it hashable, so it can be used as key:
[(tuple(val), key) for key, val in d.items())] # that would create list of pairs
But if we pass something to function, we don't need to create list, we can pass similar expression as generator comprehension, so our final code looks like:
result = dict((tuple(val), key) for key, val in d.items())
Do you know that a dict as a items function
So instead of that:
networks_to_person = {}
for person in person_to_networks:
networks = person_to_networks[person]
networks_to_person[networks] = person
You can do
networks_to_person = {}
for person, networks in person_to_networks.items():
networks_to_person[networks] = person
Which can also be written as:
networks_to_person = {networks: person for person, networks in person_to_networks.items()}
Related
So I have a list of tuples of the form:
my_list=[('a','aa','aaa',0),('a','aa','aab',1),('a','ab','aba',2)]
And I need it to convert it to a nested dictionary:
out={'a':{'aa':{'aaa':0,'aab':1},'ab':{'aba':2}}}
The crucial piece of my setting is that I do not know in advance the length of the tuples in my_list (4 is just an example). Is there an easy way to generalize the cases I saw in other answers (e.g. Python list of tuples to nested dict or Convert a list of variable length Tuples into Dictionary) beyond the fixed 3-element tuples they use?
I made various attempts with recursive functions but I do not have anything close to a solution.
Just loop over the first keys, setting aside the last pair of items which will be a key-value pair, and set dictionaries in-between (using setdefault here, but you could do that part manually):
result = {}
for *keys, last_key, value in my_list:
current = result
for key in keys:
current = current.setdefault(key, {})
current[last_key] = value
Just to be explicit by what I mean by "manually" (I guess I should rather say "explicitly"):
result = {}
for *keys, last_key, value in my_list:
current = result
for key in keys:
if key not in current:
current[key] = {}
current = current[key]
current[last_key] = value
I have a dictionary where the values are a list of tuples.
dictionary = {1:[('hello, how are you'),('how is the weather'),('okay
then')], 2:[('is this okay'),('maybe It is')]}
I want to make the values a single string for each key. So I made a function which does the job, but I do not know how to get insert it back to the original dictionary.
my function:
def list_of_tuples_to_string(dictionary):
for tup in dictionary.values():
k = [''.join(i) for i in tup] #joining list of tuples to make a list of strings
l = [''.join(k)] #joining list of strings to make a string
for j in l:
ki = j.lower() #converting string to lower case
return ki
output i want:
dictionary = {1:'hello, how are you how is the weather okay then', 2:'is this okay maybe it is'}
You can simply overwrite the values for each key in the dictionary:
for key, value in dictionary.items():
dictionary[key] = ' '.join(value)
Note the space in the join statement, which joins each string in the list with a space.
It can be done even simpler than you think, just using comprehension dicts
>>> dictionary = {1:[('hello, how are you'),('how is the weather'),('okay then')],
2:[('is this okay'),('maybe It is')]}
>>> dictionary = {key:' '.join(val).lower() for key, val in dictionary.items()}
>>> print(dictionary)
{1: 'hello, how are you how is the weather okay then', 2: 'is this okay maybe It is'}
Now, let's go through the method
we loop through the keys and values in the dictionary with dict.items()
assign the key as itself together with the value as a string consisting of each element in the list.
The elemts are joined together with a single space and set to lowercase.
Try:
for i in dictionary.keys():
dictionary[i]=' '.join(updt_key.lower() for updt_key in dictionary[i])
I'm trying to understand about dictionaries and list in Python.
Assume that I have a list which contains 3 dictionaries
Ex. item_list = [price,stock,quantity]
price, stock and quantity are the dictionaries here. Each dictionary has few key-value pairs like
price = {'toys':25,'clothes':[12,15,20]}
I know to access individual elements, I can use a for loop with the keys specified like:
for item in item_list:
print item['toys']
How do I access the elements without directly mentioning the key in the for loop?
You can iterate over a dictionary just like you can iterate over a list.
for item in item_list:
for key in item:
print item[key]
In a sense, you're still mentioning the keys, but you're not referencing them explicitly by their value.
If you're just interested in the values you can use the values() method:
for item in item_list:
for key in item.values():
print item[key]
My preferred way to iterate over dictionaries though is with items, which returns a tuple of key, value pairs.
for item in item_list:
for key, value in item.items():
print key, value
I would do something like this:
for item in item_list:
for key, value in item.iteritems():
print key, value
Let us say, you have a list like this
prices_list = [{'toys':25,'clothes':[12,15,20]},{'toys':35,'clothes':[12,15,20]}]
And you would like to get the value corresponding to toys, but without specifying the name in the for loop. So, you can use operator.itemgetter like this
from operator import itemgetter
getter = itemgetter("toys")
print [getter(item) for item in prices_list]
# [25, 35]
The same can be used like this
total = 0
for item in prices_list:
total += getter(item)
for d in item_list:
for i in d.values():
print i
You could also call d.items() and get back tuples of (key, value) if you wanted access to both.
Additionally if you don't care about readability you could use this to get a list of all the values accross the dicts in your list.
[x for y in (i.values() for i in item_list) for x in y]
You can also use: [d for i in item_list for d in i.values()] to get the values and flatten them into a list (though yours would still be nested because of clothes' value being a list.
Finally you can merge the dictionaries into one if they have distinct keys:
joint_mapping = dict([d for i in item_list for d in i.items()])
or if they don't have unique values you can use the below code to produce a dict of lists of values. :
for k, v in [d for i in item_list for d in i.items()]:
new_d[k] = new_d.get(k, [])+[v]
You mentioned :
#Eenvincible - I would be inputting those values to other variable.
Print is just an example I gave. So would not want to hardcode the key.
I think you can do your trick using for loop as mentioned in other answers.
for item in item_list:
for key in item:
print item[key]
tempvariable = item[key]
.... do something here.
If you want to assign each value to a seperate variable, you should:
- First, assign that variables to any insignificant value EX: **None** or *""*
- Then, dynamically use the for loop to reassign each variable to new value using if condition or thier index.
EX:
price_toys , price_clothes , stock_toys , stock_clothes = None , None , None , None
for item in item_list:
for key in item:
tempvariable = item[key]
# condition to choose which varible will be set to the current value.
if item == "price" and key == "toys":
price_toys = tempvariable
# and so on
Let's say I have dict. I don't know the key/value inside. How do I get this key and the value without doing a for loop (there is only one item in the dict).
You might wonder why I am using a dictionary in that case. I have dictionaries all over my API and I don't want the user to be lost. It's only a matter of consistency. Otherwise, I would have used a list and indexes.
Use the proper data type for the job. Your goal should be to have workable code, not that you use the same data type all over the place.
If your dictionary only contains one key and one value, you can get either with indexing:
key = list(d)[0]
value = list(d.values())[0]
or to get both:
key, value = list(d.items())[0]
The list calls are needed because in Python 3, .keys(), .values() and .items() return dict views, not lists.
Another option is to use sequence unpacking:
key, = d
value, = d.values()
or for both at the same time:
(key, value), = d.items()
Just get the first item in the dictionary using an iterator
>>> d = {"foo":"bar"}
>>> k, v = next(iter(d.items()))
>>> k
'foo'
>>> v
'bar'
You can do this:
>>> d={1:'one'}
>>> k=list(d)[0]
>>> v=d[k]
Works in Python 2 or 3
d.popitem() will give you a key,value tuple.
I wrote the below code working with dictionary and list:
d = computeRanks() # dictionary of id : interestRank pairs
lst = list(d) # tuples (id, interestRank)
interestingIds = []
for i in range(20): # choice randomly 20 highly ranked ids
choice = randomWeightedChoice(d.values()) # returns random index from list
interestingIds.append(lst[choice][0])
There seems to be possible error because I'm not sure if there is a correspondence between indices in lst and d.values().
Do you know how to write this better?
One of the policies of dict is that the results of dict.keys() and dict.values() will correspond so long as the contents of the dictionary are not modified.
As #Ignacio says, the index choice does correspond to the intended element of lst, so your code's logic is correct. But your code should be much simpler: d already contains IDs for the elements, so rewrite randomWeightedChoice to take a dictionary and return an ID.
Perhaps it will help you to know that you can iterate over a dictionary's key-value pairs with d.items():
for k, v in d.items():
etc.