Creating list from list of dictionaries - python

I'm tasked with creating a list of the values associated with a specific key from a list of dictionaries.
Currently, I'm two for loops and a conditional into this but I know there's a much more efficient way of going about this.
#lst = list of dict.
#k = specific key being checked for
for dict in lst:
for ind in dict:
if dict[ind] == k:
ret_val.append(dict[ind])
The instructions also state that I am to assume that all dictionaries contain the key and that the value should only be added if the value doesn't already exist.

You might be looking for this:
ret_val = [dict[ind] for dict in lst for ind in dict if dict[ind]==k]

Related

Dictionary unique values in comprehension

I have a little task which I solved.
Task: find all PAIRS in a sequence which sum up to a certain number.
For example (1,2,3,4) and target 3 yields one pair (1,2).
I came up with a solution:
def pair(lst, find):
res = []
for i in lst:
if (find - i) in lst:
res.append([(find - i),i])
return {x:y for x,y in res}
I'm a bit surprised to see the dictionary comprehension filter all duplicate solutions.
Which actually forms my question: how and why a dictionary comprehension removes duplicates?
Because dict hashes its keys then store them in a set-like data structure. As a result the newly created {key :value} overrides the older one and in your case the duplicates. I think this may be a duplicate question

Access a dictionary's keys given a list of keys using dict comprehension

I'm new to Python and I am trying to understand dictionary comprehension better. Suppose I have a dictionary with a large set of keys, and list contain a smaller subset (but a bit large) of keys in the dictionary. How would you, if it is possible, using dict comprehension, access all the values with the keys in the list?
nw_dt = {}
for i in range(101):
nw_dt[chr(i)] = randint(0, 101)
ky_lit = [chr(b) for b in range(50, 101)]
What I have tired are the following:
for kys in nw_dt:
nw_dt[f'{kys for v in ky_lit}']
But the string is a generator expression which returns a KeyError
I've also tried to search for a single key:
for kys in nw_dt:
nw_dt[f'{kys if kys == chr(51)}']
It returns a EOF parsing error for the string
You can iterate over the list in the dictionary comprehension:
{key: nw_dt[key] for key in ky_lit}
A dictionary comprehension creates a new dictionary, but it can iterate over any iterable type.

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.

Going through the last x elements in an ordered dictionary?

I want to go through an x number of the most recently added entries of an ordered dictionary. So far, the only way I can think of is this:
listLastKeys = orderedDict.keys()[-x:]
for key in listLastKeys:
#do stuff with orderedDict[key]
But it feels redundant and somewhat wasteful to make another list and go through the ordered dictionary with that list when the ordered dictionary should already know what order it is in. Is there an alternative way? Thanks!
Iterate over the dict in reverse and apply an itertools.islice:
from itertools import islice
for key in islice(reversed(your_ordered_dict), 5):
# do something with last 5 keys
Instead of reversing it like you are, you can loop through it in reverse order using reversed(). Example:
D = {0 : 'h', 1: 'i', 2:'j'}
x = 1
for key in reversed(D.keys()):
if x == key:
break
You could keep a list of the keys present in the dictionary last run.
I don't know the exact semantics of your program, but this is a function that will check for new keys.
keys=[] #this list should be global
def checkNewKeys(myDict):
for key, item in myDict.iteritems():
if key not in keys:
#do what you want with new keys
keys.append(key)
This basically keep track of what was in the dictionary the whole run of your program, without needing to create a new list every time.

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