List to Dictionary with key to be a String Counter - python-2.7

I am new to python and was trying to implement a dictionary from a list with the key value to be a string counter
ex. the list is ['a','b','c']
I want this list to be displayed as
dict {'A1':'a','A2':'b','A3':'c'}
Thanks in advance

Given I understand your question correctly you want for the i-th element, a key-value pair 'Ai':c with c the character at position i. You can use dictionary comprehension:
{'A%s'%i:e for i,e in enumerate(data,1)}
Running this in the interpreter:
>>> data = ['a','b','c']
>>> {'A%s'%i:e for i,e in enumerate(data,1)}
{'A2': 'b', 'A3': 'c', 'A1': 'a'}
This is dictionary comprehension. Dictionary comprehension has as syntax:
{key(element):value(element) for element in iterable}
Where key and value are expressions that do something with element. For each element in the iterable. It will evaluate the expression and associate the value with the derived key.

Related

Loop through dict key equals to list than put in new list

I have a rather large dictionary right now that is set up like this:
largedict = {'journalname':{code: 2065},'journalname1':{code: 3055}}
and so on and so on. And another dictionary:
codes = {3055: 'medicine',3786: 'sciences'}
And I want to loop through largedict, compare it's code value to the keys in codes. Then either add all journalname key/value pairs that match the code to a different dictionary, or delete all that don't from largedict.
new_dic = {journal_name : journal_body for journal_name, journal_body in largedict.items() if journal_body["code"] in codes}

How do I get elements from list of lists based on a index value using python?

I have lists of lists like this :
Input_list= [['a','b'],[1,6],[1,13.8]]
I have a dictionary
dictny={'a':'mdl/a','b':'mdl/b'}
I am trying to find whether keys present in dictny will be present in Input_list or not by using following code:
Key_list=[]
for key,value in dictny.iteritems():
Key_list.append(key)
Here I am appending all keys into a separate list.
for key in Key_list:
for indx,list in enumerate(Input_list):
for element_indx,element in enumerate(list):
if element == key:
print "matching key",element
print "element_index",element_indx
Here I am trying to find whether my key is present in Input_list or not and I am trying to catch the index of the matching element. Now I want to use this index and to extract corresponding elements from sublist of Input_list based on the element_indx. How can I achieve this?

Python comparing a list of tuples and a list of clustered words

I need to compare two kind of lists as follow.
List of words with their frequency
list_1=[('psicomotricita',6), ('psicomotorio',5) , ('psicomotorie',6),('psicomotore', 7),
('bella',1), ('biella',7), ('bello',3),('zorro',4)]
List of lists, where every sublist is a cluster of word by their similarity.
list_2=[['psicomotricità', 'psicomotorio','psicomotorie','psicomotore']
['bella', 'biella', 'bello']
['zorro']]
So, I need to loop every sublist of the list_2 in order to pick-up the word that compare in the list_1 with the maximum frequency.
The result should be:
final_list['psicomotore','biella','zorro']
Is there anybody who can help me? Thanks!
After a long struggle (I'm new newbie in python) I solved the problem above.
So, first I converted the list of tuples to a dictionary:
d = {t[0]:int(t[1]) for t in list_1}
Second, I have created the following function:
def SortTuples(list, dict):
final_ls= []
ddd= []
for el in list_2:
for key, value in d.iteritems():
if key in el:
ddd.append((key,value))
z= (max(ddd,key=itemgetter(1))[0])
final_ls.append(z)
ddd= []
return final_ls
The result is a list with the words whom has the max frequency:
Out: ['psicomotore', 'biella', 'zorro']

Python: Can a dictionary have both tuples and strings as key ?

Can I have a single dictionary, in which some of the keys are tuples and other are strings, at the same time ?
The only two requirements for dictionary keys in python is that they must be unique (ie - you can't use the same key twice in a single dictionary) and each key must be hashable (ie - it must have a unique id for comparison). Ints, floats, strings, dictionaries, tuples, .. etc are all hashable.
Example of using a tuple and a string as keys:
>>> mydict = {('you', 'can'):'do', 'this':('if', 'you', 'want')}
>>> print(mydict)
{'this': ('if', 'you', 'want'), ('you', 'can'): 'do'}
>>> mydict[('you', 'can')]
'do'
>>> mydict['this']
('if', 'you', 'want')
Example showing tuples and strings have a hash method :
>>> ('you', 'can').__hash__()
-5095345937749811518
>>> 'this'.__hash__()
2314053222244391272

Sorting a list in python with items that begin with specified letters

If I have a list:
list = ('john', 'adam', 'tom', 'danny')
and I want a sorted output with the items where the first letter is between 'a' and 'h', like:
('adam', 'danny', 'john')
which sorting function in Python do I need to complete this task?
This is the code i tried:
l = list()
while True:
s = raw_input("Enter a username: ")
l.append(s)
print sorted(l)
You need 2 distinct things: a list with just the elements that begin with an acceptable letter, and then the sorted version of that list. The former can be done with a list comprehension (although, as #jonrsharpe points out, you look like you want tuples, so you meat need to convert to a list & the convert the result back).