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])
Related
I'm trying to traverse through a dictionary that essentially contains tuples and keys for tuples like this:
(101940039, 'yoel'): 0.0016034940264139383,
(101940039, 'yossi'): 0.004810482079241815,
(101940039, 'youngmen'): 0.0016034940264139383}
I need to access the value of the key, i.e., the string of the tuple. I tried many things, like converting to the dictionary, using key[0] just gives me "'int' object is not subscribable"..
def matching_score(k, tokens, tf_idf_score):
print("Matching Score")
query_weights = {}
for word in tokens:
for key, value in tf_idf_score.items():
**if key in word**:
try:
query_weights[key[0]] += tf_idf_score[key]
except:
query_weights[key[0]] = tf_idf_score[key]
query_weights = sorted(query_weights.items(), key=lambda x: x[1], reverse=True)
print("")
l = []
for i in query_weights[:10]:
l.append(i[0])
print(l)
First, this is a recreation of your data as a dictionary:
d1 = {(101940039, 'yoel'): 0.0016034940264139383,
(101940039, 'yossi'): 0.004810482079241815,
(101940039, 'youngmen'): 0.0016034940264139383}
With keys() it is possible to access the keys. At the same time, we want to convert them into a list.
list(d1.keys())
The result is a list of tuples.
[(101940039, 'yoel'), (101940039, 'yossi'), (101940039, 'youngmen')]
To access individual items in this nested list: first, use the index of the list to select the desired list, and second, use the index of the tuple to select the desired item within.
list(d1.keys())[0][1]
'yoel'
To get all the string elements of the key tuples:
for i in range(len(d1)):
print(list(d1.keys())[i][1])
yoel
yossi
youngmen
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
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()}
I have this list:
source = ['sourceid', 'SubSourcePontiflex', 'acq_source', 'OptInSource', 'source',
'SourceID', 'Sub-Source', 'SubSource', 'LeadSource_295', 'Source',
'SourceCode', 'source_code', 'SourceSubID']
I am iterating over XML in python to create a dictionary for each child node. The dictionary varies in length and keys with each iteration. Sometimes the dictionary will contain a key that is also an item in this list. Sometimes it wont. What I want to be able to do is, if a key in the dictionary is also an item in this list then append the value to a new list. If none of the keys in the dictionary are in list source, I'd like to append a default value. I'm really having a brain block on how to do this. Any help would be appreciated.
Just use the in keyword to check for membership of some key in a dictionary.
The following example will print [3, 1] since 3 and 1 are keys in the dictionary and also elements of the list.
someList = [8, 9, 7, 3, 1]
someDict = {1:2, 2:3, 3:4, 4:5, 5:6}
intersection = [i for i in someList if i in someDict]
print(intersection)
You can just check if this intersection list is empty at every iteration. If the list is empty then you know that no items in the list are keys in the dictionary.
in_source_and_dict = set(mydict.keys()).intersection(set(source))
in_dict_not_source = set(mydict.keys()) - set(source)
in_source_not_dict = set(source) - set(mydict.keys())
Iterate over the result of which one you want. In this case I guess you'll want to iterate over in_source_not_dict to provide default values.
In Python 3, you can perform set operations directly on the object returned by dict.keys():
in_source_and_dict = mydict.keys() & source
in_dict_not_source = mydict.keys() - source
in_source_not_dict = source - mydict.keys()
This will also work in Python 2.7 if you replace .keys() by .viewkeys().
my_dict = { some values }
values = []
for s in sources:
if my_dict.get(s):
values += [s]
if not values:
values += [default]
You can loop through the sources array and see if there is a value for that source in the dictionary. If there is, append it to values. After that loop, if values is empty, append the default vaule.
Note, if you have a key, value pair in your dictionary (val, None) then you will not append the None value to the end of the list. If that is an issue you will probably not want to use this solution.
You can do this with the any() function
dict = {...}
keys = [...]
if not any(key in dict for key in keys):
# no keys here
Equivalently, with all() (DeMorgan's laws):
if all(key not in dict for key in keys):
# no keys here
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.