d = {"a":[1,2,3], "b":4}
I'm trying to create a nested list from d containing all pairs of key-value:
[["a",1],["a",2],["a",3],["b",4]]
Should I be using list comprehensions here, or is there a more pythonic way?
You can use a list comprehension:
d = {"a":[1,2,3], "b":4}
r = [[a, i] for a, b in d.items() for i in (b if isinstance(b, list) else [b])]
Output:
[['a', 1], ['a', 2], ['a', 3], ['b', 4]]
You can't use a list comprehension because it has to map from one item to another. You are intending to create more items than exist in the dict:
d = {"a":[1,2,3], "b":4}
result = []
for k,v in d.items():
if isinstance(v, list):
for item in v:
result.append([k,item])
else:
result.append([k,v])
def di(my_dictionary):
for key in my_dictionary:
if type(my_dictionary[key]) == list:
for item in my_dictionary[key]:
yield [key,item]
else:
yield [key,my_dictionary[key]]
and just use it by
d = {"a":[1,2,3], "b":4}
list(di(d))
Related
I have the following dictionary and list:
dict_ = {'one':['a','b','c','d','e','f'],
'two':['g','h','l','m'],
'three':['x','y','z'],
'four':['xx','yy']}
ls = ['a','x','c','h','l']
I need to loop through the dict values and check if the items in ls exist in dict values, if so I would like to return a new dict with key/pair values, as follows:
new_dict = {'one':['a','c'],'two':['h','l'], 'three':['x']}
You can check overlaps with a set intersection -
new_dict = {k: list(set(v) & set(ls)) for k, v in dct.items() if (set(v) & set(ls))}
Output
{'one': ['c', 'a'], 'two': ['l', 'h'], 'three': ['x']}
_dict = {'one':['a','b','c','d','e','f'],
'two':['g','h','l','m'],
'three':['x','y','z']}
ls = ['a','x','c','h','l']
new_dict = {k:[v for v in l if v in ls] for k,l in _dict.items()}
print(new_dict)
First, a tip: you should never call variablke as "orange names" like int, float, dict, input, exc...
The solution:
dictt = {'one':['a','b','c','d','e','f'],
'two':['g','h','l','m'],
'three':['x','y','z']}
ls = ['a','x','c','h','l']
for k, v in dictt.items():
dictt[k] = [el for el in v if el in ls]
Say that I have
function(Dict[str, List[str]] -> List[str]
how could I return a list that contains the str in the Dict with most elements in the list?
function({'a':['1','2'], 'b':['1'], 'c':['1', '2']})
['a', 'c']
The function should be able to still return the str even if more than one str has the most elements in the list just like the above example. Thank you very much in advance!
Get the max length first, then loop over the elements to filter those that have the max length:
def get_max(d):
max_len = max(map(len,d.values()))
return [k for k,v in d.items() if len(v)==max_len]
get_max({'a':['1','2'], 'b':['1'], 'c':['1', '2']})
# ['a', 'c']
One approach:
def fun(d):
current, res = 0, []
for k, v in d.items():
if len(v) > current:
res = [k]
current = len(v)
elif len(v) == current:
res.append(k)
current = len(v)
return res
final = fun({"a": ['1', '2'], "b": ['1'], "c": ['1', '2']})
print(final)
Output
['a', 'c']
Your function will look like this:
def dict_to_max_list(mydict):
for item in mydict.items():
mydict[item[0]] = len(item[1])
all_values = mydict.values()
max_value = max(all_values)
# Using list comprehension
mylist = [x[0] for x in mydict.items() if x[1] == max_value]
return mylist
The above function accepts a dict. Iterates through your dict and calculate the length of each list in your dict. And then returns list with maximum value using list comprehension.
d1 = {'a':['1','2'], 'b':['1'], 'c':['1', '2']}
list1 = dict_to_max_list(d1)
print(list1)
def function(dict_list: dict):
#set the max length to 0
greatest_length = 0
lists_with_greatest_length = []
#for each list if the length is greater than greatest_length
#we overwrite lists_with_greatest_length with the new list and take its length as the largest.
for (key, liste) in zip(dictt.keys(), dictt.values()):
if len(liste) > greatest_length:
greatest_length = len(liste)
lists_with_greatest_length = [key]
elif len(liste) == greatest_length:
lists_with_greatest_length.append(key)
return lists_with_greatest_length
I have a dictionary
my_dict = {"a":1, "b":2, "c":3}
And list
my_list = [2,3,1]
I want to replace items in my_list with keys from my_dict, something like...
my_list = [b, c, a]
How can i achieve this?
I'm sure it's possible to manufacture a list comprehension but this could be one approach (which only ever iterates over the list once and allows you to cover potential edge cases inside the loop):
for key, value in my_dict.items():
if value not in my_list:
# Does this case need special handling?
continue
index = my_list.index(value)
my_list[index] = key
There are a few edge cases to consider here, e.g. what happens if not all items match, what if the dictionary and list are of unequal lengths etc. Depending on your use case you want to make sure to cover all possible edge cases accordingly.
Applied to your example code, it yields the following output:
>>> my_dict = {"a":1, "b":2, "c":3}
>>> my_list = [2,3,1]
>>> my_dict
{'a': 1, 'b': 2, 'c': 3}
>>> my_list
[2, 3, 1]
>>> for key, value in my_dict.items():
... if value not in my_list:
... # Does this case need special handling?
... continue
... index = my_list.index(value)
... my_list[index] = key
>>> my_list
['b', 'c', 'a']
Dictionaries are mappings. You want to use reverse mappings (use values to find keys), so let's reverse the dict.
my_dict = {"a":1, "b":2, "c":3}
reversed_dict = {my_dict[k]:k for k in my_dict}
Then we just apply the dict to each element:
my_list = [2,3,1]
result = [reversed_dict[elem] for elem in my_list]
You can reverse the key value pair of your dict and then iterate your list to get the corresponding keys.
>>> rev_dict = dict((v,k) for k,v in my_dict.items())
>>> rev_dict
{1: 'a', 2: 'b', 3: 'c'}
>>> [rev_dict[x] for x in my_list]
['b', 'c', 'a']
rev = { v:k for k,v in my_dict.items()}
new_list = [rev[item] for item in my_list]
Output new_list:
['b', 'c', 'a']
This will probably work
for key, val in my_dict.items():
for i, v in enumerate(my_list):
if v == val:
my_list[i] = key
You can do this with list comprehension, what you need to do is: sort the dict.items according to your list, then return the key:
>>> my_dict = {"a":1, "b":2, "c":3}
>>> my_list = [2,3,1]
>>> [key for key, value in sorted(my_dict.items(), key = lambda x:my_list.index(x[1]))]
['b', 'c', 'a']
You can use the function itemgetter. First, you need to swap keys and values in your dictionary:
from operator import itemgetter
dct = {"a": 1, "b": 2, "c": 3}
lst = [2, 3, 1]
dct = {v: k for k, v in dct.items()}
# {1: 'a', 2: 'b', 3: 'c'}
print(list(itemgetter(*lst)(dct)))
# ['b', 'c', 'a']
dic = {('UUU','UUC'):'F',('GUU','GUC','GUA','GUG'):'V'}
L = ['UUU', 'GUG', 'GUU']
As you see each elements of list(L) are in dictionary as keys. Now i want to replace each elements of L by its corresponding values. Output would be:
output = ['F','V']
How can i do that?
One way would be to decompose the keys into individual elements, and create a new dict from those:
new_dic = {}
for k, v in dic.items():
for sub_k in k:
new_dic[sub_k] = v
Now it's a simple matter of looping through the list:
output = [new_dic[i] for i in L]
and you can de-duplicate with set:
output = list(set(output))
Using list compression:
In [1]: dic = {('UUU','UUC'):'F',('GUU','GUC','GUA','GUG'):'V'}
In [2]: L = ['UUU', 'GUG', 'GUU']
In [3]: list(set([v for k,v in dic.items() for x in L if x in k]))
Out [3]: ['V', 'F']
I have two separate Python List that have common key names in their respective dictionary. The second list called recordList has multiple dictionaries with the same key name that I want to append the first list clientList. Here are examples lists:
clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]
So the end result would be something like this so the records are now in a new list of multiple dictionaries within the clientList.
clientList = [{'client1': [['c1','f1'], [{'rec_1':['t1','s1']},{'rec_2':['t2','s2']}]]}, {'client2': [['c2','f2']]}]
Seems simple enough but I'm struggling to find a way to iterate both of these dictionaries using variables to find where they match.
When you are sure, that the key names are equal in both dictionaries:
clientlist = dict([(k, [clientList[k], recordlist[k]]) for k in clientList])
like here:
>>> a = {1:1,2:2,3:3}
>>> b = {1:11,2:12,3:13}
>>> c = dict([(k,[a[k],b[k]]) for k in a])
>>> c
{1: [1, 11], 2: [2, 12], 3: [3, 13]}
Assuming you want a list of values that correspond to each key in the two lists, try this as a start:
from pprint import pprint
clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]
clientList.extend(recordList)
outputList = {}
for rec in clientList:
k = rec.keys()[0]
v = rec.values()[0]
if k in outputList:
outputList[k].append(v)
else:
outputList[k] = [v,]
pprint(outputList)
It will produce this:
{'client1': [['c1', 'f1'], {'rec_1': ['t1', 's1']}, {'rec_2': ['t2', 's2']}],
'client2': [['c2', 'f2']]}
This could work but I am not sure I understand the rules of your data structure.
# join all the dicts for better lookup and update
clientDict = {}
for d in clientList:
for k, v in d.items():
clientDict[k] = clientDict.get(k, []) + v
recordDict = {}
for d in recordList:
for k, v in d.items():
recordDict[k] = recordDict.get(k, []) + [v]
for k, v in recordDict.items():
clientDict[k] = [clientDict[k]] + v
# I don't know why you need a list of one-key dicts but here it is
clientList = [dict([(k, v)]) for k, v in clientDict.items()]
With the sample data you provided this gives the result you wanted, hope it helps.