Transform dictionary key-value pairs to list of tuples - python

I have a dictionary of lists:
dic = {'contig_100003': ['contig_14576'], 'contig_100022': ['contig_96468'], 'contig_100023': ['contig_24939', 'contig_33444', 'contig_72441']}
And I would like to get a list (including the key) of it:
List = [(contig_100003','contig_14576'), (contig_100022','contig_96468'), (contig_100023','contig_24939', 'contig_33444', 'contig_72441')]
However, my code cannot get rid of the internal/value list:
list(dic.items())
[('contig_100003', ['contig_14576']),
('contig_100022', ['contig_96468']),
('contig_100023', ['contig_24939', 'contig_33444', 'contig_72441'])]

This might solve it
[(k, *v) for k, v in dic.items()]

You can use tuple concatenation to get the desired output:
result = [(key,) + tuple(value) for key, value in dic.items()]
print(result)
This outputs:
[('contig_100003', 'contig_14576'), ('contig_100022', 'contig_96468'),
('contig_100023', 'contig_24939', 'contig_33444', 'contig_72441')]

Related

Create dictionary from dict and list

I have a dictionary :
dicocategory = {}
dicocategory["a"] = ["crapow", "Killian", "pauk", "victor"]
dicocategory["b"] = ["graton", "fred"]
dicocategory["c"] = ["babar", "poca", "german", "Georges", "nowak"]
dicocategory["d"] = ["crado", "cradi", "hibou", "distopia", "fiboul"]
dicocategory["e"] = ["makenkosapo"]
and a list :
my_list = ['makenkosapo', 'Killian', 'Georges', 'poca', 'nowak']
I want to create a new dictionary with my dicocategory's keys as new keys and items of my list as values.
To get the keys of my new dict (removing duplicate content and adapted to my list) I made :
def tablemain(my_list ):
tableheaders = list()
for value in my_list:
tableheaders.append([k for k, v in dicocategory.items() if value in v])
convertlist = [j for i in tableheaders for j in i]
headerstablefinal = list(set(convertlist))
return headerstablefinal
giving me:
['e', 'a', 'c']
My problem is: I don't know how to put the items of my list in the corresponding keys.
EDIT :
Bellow an output of what I want
{"a" : ['Killian'], 'c' : ['Georges', 'poca', 'nowak'], 'e' : ['makenkosapo']}
The list my_list can change, so I want something that can create a new dictionary doesn't matter the list.
If my new list is :
my_list = ['crapow', 'german', 'pauk']
My output will be :
{'a':['crapow', 'pauk'], 'c':['german']}
Do you have any idea?
Thank you
You can use a couple of dictionary comprehensions. Calculate the intersection in the first, and in the second remove instances where the intersection is empty:
my_set = set(my_list)
# calculate intersection
res = {k: set(v) & my_set for k, v in dicocategory.items()}
# remove zero intersection values
res = {k: v for k, v in res.items() if v}
print(res)
{'a': {'Killian'},
'c': {'Georges', 'nowak', 'poca'},
'e': {'makenkosapo'}}
More efficiently, you can use a generator expression to avoid an intermediary dictionary:
# generate intersection
gen = ((k, set(v) & my_set) for k, v in dicocategory.items())
# remove zero intersection values
res = {k: v for k, v in gen if v}
You can get a dictionary containing only keys with values that match your list like this:
{k:v for k,v in dicocategory.items() if set(v).intersection(set(my_list))}
You won't be able to put that directly into a DataFrame though as the lists differ in length.

Python: How to combine two dictionaries in python such that the resultant contains key as the value from the first

I have two dictionaries as follows:
mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}
The resultant dictionary should be such that it takes the key as the value of first dictionary.
Result_dictionary= {'apple':50, 'banana':30}
You can use a dictionary comprehension using the values of the first dictionary as the keys of the resulting dictionary. This assumes all keys of the first are present in the second dict
{v: dict2[k] for k, v in dict1.items()}
you can also add a check for the presence of the keys in the second dictionary
{v: dictionary_2[k] for k, v in dictionary_1.items() if k in dictionary_2}
Loop through one of the dictionaries and check if the value for a key in mydictionary_1 exists in mydictionary_2.
You can achieve this using python's dictionary comprehension -
Result_dictionary = { v:mydictionary_2[k] for k,v in mydictionary_1.iteritems() if k in mydictionary_2.keys()}
To see how this list comprehension is working you can even use general for loop to loop through each key, value pair in mydictionary_1
for key,value in mydictionary_1.iteritems():
if key in mydictionary_2.keys():
Result_dictionary[value]=mydictionary_2[key]
Dictionary comprehension is an ideal solution for this one, as previously mentioned. Here is a for loop example:
def combine_dictionaries(dict1, dict2):
result_dictionary = {}
for key in dict1.keys():
result_dictionary[dict1[key]] = dict2[key]
return result_dictionary
combine_dictionaries({1:'apple', 2:'banana'}, {1:50, 2:30})
>>>{'apple': 50, 'banana': 30}
This assumes all values of the dict1 are present in the dict2.
def dict_cross_match(dict1, dict2):
new_dict = {}
for item in dict1.keys():
if item in dict2.keys():
new_dict[dict1[item]] = dict2[item]
return new_dict
mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}
print(dict_cross_match(mydictionary_1, mydictionary_2))

How to split list inside a dictionnary to create a new one?

I've been struggling on something for the day,
I have a dictionnary under the format
dict = {a:[element1, element2, element3], b:[element4, element5, element6]...}
I want a new dictionnary under the form
newdict = {a:element1, b:element4...}
Meaning only keeping the first element of the lists contained for each value.
You can use a dictionary comprehension:
{k: v[0] for k, v in d.items()}
# {'a': 'element1', 'b': 'element4'}
Hopefully this helps.
I like to check if the dictionary has a key before overwriting a keys value.
dict = {a:[element1, element2, element3], b:[element4, element5, element6]}
Python 2
newDict = {}
for k, v in dict.iteritems():
if k not in newDict:
# add the first list value to the newDict's key
newDick[k] = v[0]
Python 3
newDict = {}
for k, v in dict.items():
if k not in newDict:
# add the first list value to the newDict's key
newDick[k] = v[0]

Removing key values pairs from a list of dictionaries

I have a list of dictionaries such as:
[{'mykey1':'myvalue1', 'mykey2':'myvalue2'}, {'mykey1':'myvalue1a', 'mykey2':'myvalue2a'}]
I need to remove all key values pairs from all dictionaries where the key is equal to mykey1. I could do this by looping through and using the del statement, but I am wondering how I would create a new list using list comprehensions or lambdas which would just remove all key value pairs where the key was mykey1.
Many thanks
If you really want to use a list comprehension, combine it with a dict comprehension:
[{k: v for k, v in d.iteritems() if k != 'mykey1'} for d in mylist]
Substitute .iteritems() for .items() if you are on python 3.
On python 2.6 and below you should use:
[dict((k, v) for k, v in d.iteritems() if k != 'mykey1') for d in mylist]
as the {key: value ...} dict comprehension syntax was only introduced in Python 2.7 and 3.
def new_dict(old_dict):
n = old_dict.copy()
n.pop('mykey1',None)
return n
new_list_of_dict = map(new_dict,list_of_dict)
or
new_list_of_dict = [ new_dict(d) for d in list_of_dict ]
Rather than using del, I opted for dict.pop since pop will suppress the KeyError if the key doesn't exist.
If you really only want to get certain keys, this becomes a bit easier.
from operator import itemgetter
tuple_keys = ('key1','key2','key3')
get_keys = itemgetter(*tuple_keys)
new_dict_list = [ dict(zip(tuple_keys,get_keys(d)) for d in old_dict_list ]
which raises KeyError if the keys aren't in the old dict
Or:
new_dict_list = [ dict( (k,d.get(k,None)) for k in tuple_keys ) for d in old_dict_list ]
which will also add key:None if key isn't in the old dict. If you don't want that None, you could do:
new_dict_list = [ dict( (k,d[k]) for k in tuple_keys if k in d) for d in old_dict_list ]
Depending on what percent of the dictionary you're including/excluding and the size of the dictionaries, this might be slightly faster than the solution by #MartijnPieters.
You can follow this simple step :
arr = [{'mykey1':'myvalue1', 'mykey2':'myvalue2'}, {'mykey1':'myvalue1a', 'mykey2':'myvalue2a'}]
for i in arr:
del i["mykey1"]
print(arr)
output:
[{'mykey2': 'myvalue2'}, {'mykey2': 'myvalue2a'}]
On python 3.5 this works successfully
'''result is my list dict'''
[{key: value for key, value in dict.items() if key != 'EQUITY'} for dict in result]
[d.pop('mykey1', None) for d in list]

Python dictionary: Remove all the keys that begins with s

I've got a dictionary like
dic = {'s_good': 23, 's_bad': 39, 'good_s': 34}
I want to remove all the keys that begins with 's_'
So in this case first two will be removed.
Is there any efficient way to do so?
This should do it:
for k in dic.keys():
if k.startswith('s_'):
dic.pop(k)
for k in dic.keys():
if k.startswith('s_'):
del dic[k]
* EDIT *
now in python 3 , years after the original answer, keys() returns a view into the dict so you can't change the dict size.
One of the most elegant solutions is a copy of the keys:
for k in list(dic.keys()):
if k.startswith('s_'):
del dic[k]
With python 3 to avoid the error:
RuntimeError: dictionary changed size during iteration
This should do it:
list_keys = list(dic.keys())
for k in list_keys:
if k.startswith('s_'):
dic.pop(k)
You can use a dictionary comprehension:
dic = {k: v for k, v in dic.items() if not k.startswith("s_")}
Note that this creates a new dictionary (which you then assign back to the dic variable) rather than mutating the existing dictionary.
How about something like this:
dic = dict( [(x,y) for x,y in dic.items() if not x.startswith('s_')] )

Categories