Access dictionary value when the key is a tuple - python

I'm new to Python and I have a problem where I need to get the value from a dictionary where the keys are tuples. For example:
ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}
I know that each number appears ones in the keys, and I want to access the value where the key has the number 2 in (the value will be 3).
Can I get any help on how to access this value?

You could "flatten" the dictionary using the following comprehension:
ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}
flat = {element: value for key, value in ones.items() for element in key}
Now you can get the value of any key from the tuples via flat.

You can iterate ones and check if 2 is present in the key
In [24]: ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}
In [25]: for k, v in ones.iteritems():
....: if 2 in k:
....: print v
....:
3

You can't use the normal dictionary access when you are looking for one subelement of a key. You'll have to loop:
value_for_2 = next(ones[key] for key in ones if 2 in key)
would find the first match (where 'first' is arbitrary, as dictionaries are not ordered).
If your tuple elements really are unique, and you need to do multiple look-ups, then convert your dictionary first to use the tuple elements as keys instead:
converted = {t_elem: value for key in ones for t_elem in key}
Don't worry about the value duplication here. Values don't need to be unique, and all you do is store references; the above won't create copies of the values.
Now you can use fast key lookups again:
value_for_2 = converted[2]

ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}
for key, value in ones.items():
if 2 in key:
print(value)
out:
3

Related

Getting keys and values of dictionary if key in list

So I have a dictionary names "ngrams_count". I want to find all keys in this dictionary that are in a list called "words_to_find". I would also like to return the values associated with those keys.
So far, this is what I'm working with
ideasrep = [key for key in words_to_find if key in ngrams_count]
That returns only the keys that are found in the word list.
I'm also looking for a way to return only the key/values pairs for which the value is greater than one. I've tried a similar technique as this:
[(key,values) for key, values in ngrams_count.items() if values > 1]
However, this only seems to work if I stay within the dictionary and I'm running out of ideas... Ideally, I'd like a way to do these two things simultaneously.
Your first version is almost right, you just need to add ngrams_count[key] to the result.
ideasrep = [(key, ngrams_count[key]) for key in words_to_find if key in ngrams_count]
Or you can use the second version, but change the condition to check if the key is in words_to_find.
[(key,values) for key, values in ngrams_count.items() if key in words_to_find]
If words_to_find is big, you should convert it to a set before the list comprehension to make the second version more efficient.

How can I handle only the first part of my value list of a dictionary in Python?

I have a dictionary which has a list of values and I want to use only the first value of each pair before the first comma. Is that possible?
If you came across anything similar please write it down
The output you expect is unclear. If you want a dictionary in which you only keep the first item of the sublist, use a dictionary comprehension:
Assuming dic1 the input.
dic2 = {k:v[0][0] for k,v in dic1.items()}
if you have a dictionary d, then use
d.keys() to return the keys of your dictionary, which is the first item in each key value pair that makes up a dictionary
It's definitely possible.
I'll assume for now that by: "I want to use only the first value of each pair",
you mean you want to extract the first value of each pair from the dict.
Now, the answer to that depends slightly on what you ment by "pair".
If you ment the items you can get out of the items method on the dict, then the simplest way to get the first element of each of these pairs would be the keys method, also directly on the dict. In code:
def get_fist_from_pair(d: dict):
return d.keys()
In the image you provided, the values stored in the dict are lists of each length 1, filled with another list. If this inner list is what you ment by "pairs", the code would be slightly different:
def get_fist_from_pair(d: dict):
return [v[0][0] for v in d.values()]
This code looks at each value and extracts the first element of the inner list.
In case that this interpretation of pair is correct, but you also want to associate the key with that element in a new dict, the code for it would be:
def get_first_from_pair(d: dict):
return {key: d[key][0][0] for key in d}

How do I compare the values mapped to keys in a dictionary with elements in list to avoid redundancy?

I currently have a list which stores the URLs that I have read from a file. I then made a dictionary by mapping those URLs to a simple key (0,1,2,3, etc.).
Now I want to make sure that if the same URL shows up again that it doesn't get mapped to a different key. So I am trying to make a conditional statement to check for that. Basically I want to check if the item in the list( the URL) is the same as the value of any of the keys in the dictionary. If it is I don't want to add it again since that would be redundant.
I'm not sure what to put inside the if conditional statement for this to work.
pairs = {} #my dictionary
for i in list1:
if ( i == t for t in pairs ):
i = i +1
else:
pairs[j] = i
j = j + 1
Any help would be appreciated!
Thank you.
This might be what you're looking for. It adds the unique values to pairs, numbering them starting at zero. Duplicate values are ignored and do not affect the numbering:
pairs = {}
v = 0
for k in list1:
if k not in pairs:
pairs[k] = v
v += 1
To map items in a list to increasing integer keys there's this delightful idiom, which uses a collections.defaultdict with its own length as a default factory
import collections
map = collections.defaultdict()
items = 'aaaabdcdvsaafvggddd'
map.default_factory = map.__len__
for x in items:
map[x]
print(map)
You can access all values in your dict (pairs) by a simple pairs.values(). In your if condition, you can just add another condition that checks if the new item already exists in the values of your dictionary.

Iterating through a dictionary that starts at the first key value each iteration

I have a dictionary that contains usernames in the key, and dates in the value. Because I cannot sort the dictionary alphabetically, I want to iterate through the dictionary keys (username) to match an item in a separate alphabetical ordered list that holds all the usernames and then print the associated value (date) in a spreadsheet. The problem I am running into is that when it is iterating through the dictionary, it doesn't start at the beginning dictionary key each time and the next item to match in the list has already been iterated through in the dictionary. Is there a specific iteration tool that will start at the beginning each time?
Code I have so far:
x=0
nd=0
for k, v in namedatedict.items():
if k == usernamelist[x]:
sh1.write(nd, col3_name, v)
x += 1
nd += 1
To give you some background on what I am doing, I am trying to find the date that matches the specific username and print it next to the associated username in a spreadsheet. There may be a completely different way to iterate through these value but this is the only way I could think of. Any help/guidance would be appreciated.
Based on your answer to my comment, it seems that really the only reason you have the alphabetical list is to get sort-order. In that case, this problem becomes much simpler; Python supports sorting lists of tuples by one of their elements via the sorted() method. And dictionaries can provide a list of key-value tuples via the items() method. So, this just becomes:
for name, date in sorted(namedatedict.items(), key = lambda entry: entry[0]):
# do whatever you need with the name and date. Names will be alphabetical.
What about something like that:
for k in usernamelist:
sh1.write(nd, col3_name, namedatedict[k])
x += 1
nd += 1
This will iterate through the list of keys ("username") -- and get each value from the dictionary based on that key.
If usernamelist is not a proper sub-set of the keys of namedatedict, you should use get to get the value an be prepared to handle the case of non-existent key:
for k in usernamelist:
value = namedatedict.get(k)
if value is not None:
sh1.write(nd, col3_name, value)
x += 1
nd += 1
you could handle that using exception too:
for k in usernamelist:
try:
sh1.write(nd, col3_name, namedatedict[k])
x += 1
nd += 1
except KeyError:
pass
Finally, if you don't need to maintain a separate list to get keys in order, you could use sorted on the keys:
for k in sorted(namedatedict.keys())
sh1.write(nd, col3_name, namedatedict[k])
x += 1
nd += 1

search a dict keys in python

How do I search a dictionary of bigrams for a key if it exists or not and print it's value if does?
wordsCounts = {('the','computer'): 2 , ('computer','science'): 3 , ('math','lecture'): 4, ('lecture','day'): 2}
So, I want to search if the pair ('math','lecture') exists or not?
pair = ['computer','science']
for k in wordscount.keys():
if wordscount[k] == pair:
print wordscount[v]
So the result will be a list ('computer','science'): 3
Just test if the tuple of the pair exists:
if tuple(pair) in wordscount:
print wordscount[tuple(pair)]
There is no need to loop through all the keys in the dictionary; a python dictionary is much more efficient at finding matching keys if you just give it the key to look for, but it has to be the same type. Your dictionary keys are tuples, so look use a tuple key when searching.
In fact, in python dictionaries, lists are not allowed as keys because they are mutable; you would not be able to search for keys accurately if the keys themselves can be changed.
First you may want to know why it does not work..
for k in wordscount.keys():
if wordscount[k] == pair:
wordscount.keys() will return you list of tuple and next line is to compare value of dict wordsCount to a list 'pair.
Solution is
for k in wordscount.keys():
if k == tuple(pair):
print workscount[k]

Categories