How can I create a dictionary out of the a in python?
If I have a list like this:
a = ["Albert Einstein", "Nils Bohr"]
And I want it to become this:
b = {'Albert Eienstein': ['Albert', 'Eienstein'], 'Neils Bohr': ['Neils', 'Bohr']}
lista = ["Albert Eienstein","Neils Bohr"]
dictb = {}
for elem in lista:
dictb[elem] = elem.split(' ')
print dictb
Output: {'Neils Bohr': ['Neils', 'Bohr'], 'Albert Eienstein': ['Albert', 'Eienstein']}
I don't understand your question. Are you saying that you want this?
list_of_lists = [['Albert', 'Einstein'], ['Neils', 'Bohr']]
Or this?
dict_of_lists = {'Albert Einstein':['Albert', 'Einstein'],
'Neils Bohr':['Neils', 'Bohr']}
Or are you saying you want to convert from one to the other?
>>> l = ["Albert Eienstein", "Neils Bohr"]
>>> d = dict((i, i.split()) for i in l)
>>> d
{'Neils Bohr': ['Neils', 'Bohr'], 'Albert Eienstein': ['Albert', 'Eienstein']}
Just put the list inside the other, ie
scientists = [["Albert","Einstein"],["Neils","Bohr"]]
Related
Let's say I have two lists like this:
list_all = [[['some_item'],'Robert'] ,[['another_item'],'Robert'],[['itemx'],'Adam'],[['item2','item3'],'Maurice]]
I want to combine the items together by their holder (i.e 'Robert') only when they are in separate lists. Ie in the end list_all should contain:
list_all = [[['some_name','something_else'],'Robert'],[['itemx'],'Adam'],[['item2','item3'],'Maurice]]
What is a fast and effective way of doing it?
I've tried in different ways but I'm looking for something more elegant, more simplistic.
Thank you
Here is one solution. It is often better to store your data in a more structured form, e.g. a dictionary, rather than manipulate from one list format to another.
from collections import defaultdict
list_all = [[['some_item'],'Robert'],
[['another_item'],'Robert'],
[['itemx'],'Adam'],
[['item2','item3'],'Maurice']]
d = defaultdict(list)
for i in list_all:
d[i[1]].extend(i[0])
# defaultdict(list,
# {'Adam': ['itemx'],
# 'Maurice': ['item2', 'item3'],
# 'Robert': ['some_item', 'another_item']})
d2 = [[v, k] for k, v in d.items()]
# [[['some_item', 'another_item'], 'Robert'],
# [['itemx'], 'Adam'],
# [['item2', 'item3'], 'Maurice']]
You can try this, though it's quite similar to above answer but you can do this without importing anything.
list_all = [[['some_item'], 'Robert'], [['another_item'], 'Robert'], [['itemx'], 'Adam'], [['item2', 'item3'], 'Maurice']]
x = {} # initializing a dictionary to store the data
for i in list_all:
try:
x[i[1]].extend(i[0])
except KeyError:
x[i[1]] = i[0]
list2 = [[j, i ] for i,j in x.items()]
list_all = [[['some_item'],'Robert'] ,[['another_item'],'Robert'],[['itemx'],'Adam'],[['item2','item3'],'Maurice']]
dict_value = {}
for val in list_all:
list_, name = val
if name in dict_value:
dict_value[name][0].extend(list_)
else:
dict_value.setdefault(name,[list_, name])
print(list(dict_value.values()))
>>>[[['some_item', 'another_item'], 'Robert'],
[['itemx'], 'Adam'],
[['item2', 'item3'], 'Maurice']]
Given lists(a list can have an element that is in another list) and a string, I want to find all names of lists that contains a given string.
Simply, I could just go through all lists using if statements, but I feel that there is more efficient way to do so.
Any suggestion and advice would be appreciated. Thank you.
Example of Simple Method I came up with
arrayA = ['1','2','3','4','5']
arrayB = ['3','4','5']
arrayC = ['1','3','5']
arrayD = ['7']
foundArrays = []
if givenString in arrayA:
foundArrays.append('arrayA')
if givenString in arrayB:
foundArrays.append('arrayB')
if givenString in arrayC:
foundArrays.append('arrayC')
if givenString in arrayD:
foundArrays.append('arrayD')
return foundArrays
Lookup in a list is not very efficient; a set is much better.
Let's define your data like
data = { # a dict of sets
"a": {1, 2, 3, 4, 5},
"b": {3, 4, 5},
"c": {1, 3, 5},
"d": {7}
}
then we can search like
search_for = 3 # for example
in_which = {label for label,values in data.items() if search_for in values}
# -> in_which = {'a', 'b', 'c'}
If you are going to repeat this often, it may be worth pre-processing your data like
from collections import defaultdict
lookup = defaultdict(set)
for label,values in data.items():
for v in values:
lookup[v].add(label)
Now you can simply
in_which = lookup[search_for] # -> {'a', 'b', 'c'}
The simple one-liner is:
result = [lst for lst in [arrayA, arrayB, arrayC, arrayD] if givenString in lst]
or if you prefer a more functional style:
result = filter(lambda lst: givenString in lst, [arrayA, arrayB, arrayC, arrayD])
Note that neither of these gives you the NAME of the list. You shouldn't ever need to know that, though.
Array names?
Try something like this with eval() nonetheless using eval() is evil
arrayA = [1,2,3,4,5,'x']
arrayB = [3,4,5]
arrayC = [1,3,5]
arrayD = [7,'x']
foundArrays = []
array_names = ['arrayA', 'arrayB', 'arrayC', 'arrayD']
givenString = 'x'
result = [arr for arr in array_names if givenString in eval(arr)]
print result
['arrayA', 'arrayD']
In python,
I have a dictionary composed of the following:
[ ['FOXP2_MOUSE', 'AminoAcidSequence1'], ['FOXP2_RAT','AminoAcidSequence2'], ['FOXP2_DOG', 'AminoAcidSequence3'] ].
I'm trying to remove the keyed FOXP2_DOG from the dictionary and place it in a new dictionary alone. I've tried different methods: del and .remove to no avail.
like this:
>>> my_list= [ ['FOXP2_MOUSE', 'AminoAcidSequence1'], ['FOXP2_RAT','AminoAcidSequence2'], ['FOXP2_DOG', 'AminoAcidSequence3'] ]
>>> my_dict = dict(my_list)
>>> my_dict
{'FOXP2_RAT': 'AminoAcidSequence2', 'FOXP2_MOUSE': 'AminoAcidSequence1', 'FOXP2_DOG': 'AminoAcidSequence3'}
>>> my_new_dict = {}
>>> my_new_dict['FOXP2_MOUSE'] = my_dict.pop('FOXP2_MOUSE')
>>> my_dict
{'FOXP2_RAT': 'AminoAcidSequence2', 'FOXP2_DOG': 'AminoAcidSequence3'}
>>> my_new_dict
{'FOXP2_MOUSE': 'AminoAcidSequence1'}
my_data = [ ['FOXP2_MOUSE', 'AminoAcidSequence1'], ['FOXP2_RAT','AminoAcidSequence2'], ['FOXP2_DOG', 'AminoAcidSequence3'] ]
def custom_filter_data(data, key):
final_res = []
for i in range(len(data)):
if data[i][0] == key:
final_res.append(data[i])
del data[i]
return data, final_res
results = custom_filter_data(my_data,'FOXP2_DOG')
old = results[0]
new = results[1]
print old
print new
I have a python list as follows:
mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]
I would like to split it into a list based on column 2 == 'CA'
Desired Output:
filtered_list = [('Item A','CA','10'),('Item C','CA','14')]
My Attempt: Clearly there are some issues here!
mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]
filtered_list[]
for row in mylist:
if [row:1] = 'CA'
filtered_list.append(mylist[row])
You can use list comprehension to achieve this:
mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]
filtered_list = [item for item in mylist if item[1]=='CA']
You can use python's filter for this purpose in the following way.
filtered_list = list(filter(lambda x: x[1] =='CA',mylist)))
Instead of writing my own answer I would like to point out where you went wrong with an explanation.
mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]
filtered_list[] ## I believe this was typo
for row in mylist:
if [row:1] = 'CA' ## this where you missed it!
filtered_list.append(mylist[row])
I have corrected your code.
mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]
filtered_list = [] ## list created
for row in mylist:
if row[1] == 'CA': ## == for if condition and :
filtered_list.append(row) ## appending the row if row[1] == "CA"
print filtered_list
I am using pyton 3.2
I have the following dictionary:
a = {"fruits":["apple","mangoes","grapes"],"colour":["apple","orange","grapes"],"number":["1","2","3"]}
I need to iterate over this list of dictionary and I want to create a new dictionary b in which values in fruits is the same value in colours:
b = {"fruits":["apple","grapes"],"colour":["apple", "grapes"],"number":["1","3"]}
i was thinking this could work but am lost from then on:
b = {}
for item in a:
if x in a[item]:
...... dont know what to do now?
How can i do this without using itertools at all?
Is there a general function that i can use for any dictionary besides the one that i have listed?
Something like this?
a = {"fruits":["apple","mangoes","grapes"],"colour":["apple","orange","grapes"]}
b = {}
b['fruits'], b['colour'] = [], []
for fruit in a['fruits']:
if fruit in a['colour']:
b['fruits'].append(fruit)
b['colour'].append(fruit)
If you dont want numbers in the result dictionary, you can do it this way...
Code:
a = {"fruits":["apple","mangoes","grapes"],"colour":["apple","orange","grapes"],"number":["1","2","3"]}
b = dict()
b['fruits'] = b['colour'] = [x for x in a['fruits'] if x in a['colour']]
print b
Output:
{'colour': ['apple', 'grapes'], 'fruits': ['apple', 'grapes']}
Hope this helps :)
In this case, you're better off using a set:
b = {"fruits": list(set(a['fruits']).intersection(a['colour'])}
b['colour'] = b['fruits'] # or maybe make a copy here...
b = {}
for fruit in a['fruits']:
if fruit in a['colour']:
b.setdefault('fruits', []) # set if key is not present
b.setdefault('colour', [])
b.setdefault('number', [])
b['fruits'].append(fruit)
b['colour'].append(fruit)
b['number'].append(a['number'][a['fruits'].index(fruit)])