Python - Swap a value for a dictionary item - python

So basically, I have my dictionary, which looks like this:
{'my': 2, 'Phil.': 10, 'name': 3, 'Andy.': 5, 'Hello': 1, 'is': 4}
and a string that looks like this:
1 2 3 4 5 1 2 3 4 10
How can I make it so each number in the string is replaced by the word with the same number in the dictionary? So it would make the sentence:
Hello my name is Andy. Hello my name is Phil.
I have no idea how to approach this, so help is appreciated.

First make from your string a list.
list_name = string_name.split(' ')
Then switch the keys and the values from your dict (if using python 3.x use iter instead of iteritems)
my_dict = {y:x for x,y in my_dict.iteritems()}
Then you can iter tro your code
for numbers in list_name:
print(my_dict[int(numbers)])

Related

How to evaluate strings and use them as data names?

What I would like to do is evaluate strings and convert them in data types like,
If I have a string x = "helloW" and then read the value of x and make a list/function with the name helloW because the value of x is helloW. Suppose I have a file with many words and each line has a word and a number like:
lorem 1
ipsum 2
pac 3
heg 5
dis 7
Is there a way to make variables with name the words and value as numbers?
We can use a for loop and int(), but how do we name the variables?
Is there any way to do so in python?
You can use global() or a dictionary (code almost looks the same)
Creates variables
# directly create global vartiables
for every_line in input:
var_name, var_value = every_line.split()
globals()[var_name]=var_value
print(lorem, ipsum)
1 2
Creates a dictionary
my_variables = {} #empty dictionary
for every_line in input:
var_name, var_value = every_line.split()
my_variables[var_name]=var_value
print(my_variables)
{'lorem': '1', 'ipsum': '2', 'pac': '3', 'heg': '5', 'dis': '7'}
The pythonic way would be to use a dictionary!
globals() actually returns a dictionary representing the current global symbol table. That is why the code is so similar!
Instead of creating a new variable, you can store the variables in a dictionary.
vars = {}
for line in input:
name, value = line.split(' ')
vars[name] = int(value)
Now the dictionary vars will look like this.
>>> vars
{'lorem': 1, 'ipsum': 2, 'pac': 3, 'heg': 5, 'dis': 7}

How can i find the length of dictionary which consists list and again dictionary

Find the length of given list of dictionary
x= {
'output':[
{
'frame':{'enc':1,'time':2}, 'eth':{'di':1,'ghg':5}
},
]
}
How can I find the length of 'x' using Python 3.6.0
len(x) doesn't work I have tried already.
Can anyone suggest an other way?
we call this normal dictionary where you have your value as list.
printing the length of x works fine for me.
x= {'output':[{'frame':{'enc':1,'time':2}, 'eth':{'di':1,'ghg':5}},]}
print(len(x))
I am getting output as 1
Explanation:-
you define a dictionary named x which is a dictionary in which you are trying to get the the length of x since it have only one key/value pair i.e 'output' so it will give length of 1 .
if you want to print the length of the list which is treated as the value of output key you can do it like this:-
x= {'output':[{'frame':{'enc':1,'time':2}, 'eth':{'di':1,'ghg':5}},]}
print(len(x['output'][0]))
you'll get 2 as an output.
if you need further explanation you can comment the same below.
Happy coding :-)
len(x) works fine. What exactly is ur issue?
>>> x = {'output':[{'frame':{'enc':1,'time':2}, 'eth':{'di':1,'ghg':5}},]}
>>> len(x)
1
>>> len(x.keys())
1
>>> len(x.values())
1
>>> x.values()
dict_values([[{'frame': {'enc': 1, 'time': 2}, 'eth': {'di': 1, 'ghg': 5}}]])
>>> len(x['output'])
1
>>> x['output']
[{'frame': {'enc': 1, 'time': 2}, 'eth': {'di': 1, 'ghg': 5}}]
>>>
n = sum([len(v)+1 for k, v in x.items()])
print((n))
This worked for me. After trying to figure out what I actually wanted in return from len(x) the above solution came handy.
I took the solution from here: Get the number of all keys in a dictionary of dictionaries in Python.

How to create a function that loops through both the key and item of a dictionary using variables in Python?

I have a dictionary:
d1 = {'a': [2, 10], 'b': [-4, 5.5]}
I want to write a function that prints this:
table 1 2 10
table 2 -4 5.5
The following works, but there is a problem because it is not universal enough for my needs:
def f1(x):
for i in x:
print('table ',i,x[i][0],x[i][1])
f1(d1)
Output:
table 1 2 10
table 2 -4 5.5 # worked!! But not universal :(
The problem is that in the print line, the 0 and 1 have to be inserted manually.
I am trying to make the function more universal, meaning it should be able to handle more than two keys. So a ā€˜cā€™ could be in the dictionary from the beginning with another list of numbers associated with it for example.
And I want the function to handle more than just two items in each list, so 2,10 for key ā€˜aā€™ could instead be 2,10,15,14 from the beginning for example.
So, if I could make the 0 and 1 in the print line a variable that would be great, if I use something like x[i][j], where j is coming from a another loop or some where that is keeping track of the index value of the items in the lists in the dictionary.
Thanks.
Solution
Try this:
for i, k in enumerate(sorted(d1.keys()), 1):
print('table', i, *d1[k])
Output:
table 1 2 10
table 2 -4 5.5
In Steps
Dictionaries are not ordered. So sorting the keys with sorted(d1.keys()) provides a consistent order of the printed rows. You can use enumerate(iterable, 1) to start counting with 1. Here i will hold this number. d1[k] gives you the value, i.e.each list in your dictionary. The * in *d1[k] will unpack the entries from the list in the print() function. This has the same effect as writing:
print('table', i, d1[0], d1[1])
where the index inside the [] will go from 0 to len(d1) - 1.
maybe something like this:
d = {'a': [2, 10], 'b': [-4, 5.5]}
for i, k in enumerate(d):
print (i + 1), d[k]
After you can adjust but enumerate is clearly what you need
Please try this approach (python 2.7):
d1={'a': [2, 10], 'b': [-4, 5.5]}
def f1(x):
for i, v in enumerate(x.values()):
print 'table', i+1, ' '.join( map(str, v))
f1(d1)
Output:
table 1 2 10
table 2 -4 5.5

How do I fix the error "unhashable type: 'list'" when trying to make a dictionary of lists?

I'm trying to make a dictionary of lists. The input I am using looks like this:
4
1: 25
2: 20 25 28
3: 27 32 37
4: 22
Where 4 is the amount of lines that will be outputted in that format. The first thing I did was remove the "#: " format and simply kept each line like so:
['25']
['20','25','28']
['27','32','37']
['22']
So finally the goal was to take those values and put them into a dictionary with their assigned value in the dictionary being the length of how many numbers they held.
So I wanted the dictionary to look like this:
['25'] : 1
['20','25','28'] : 3
['27','32','37'] : 3
['22'] : 1
However, when I tried to code the program, I got the error:
TypeError: unhashable type: 'list'
Here is my code:
def findPairs(people):
pairs = {}
for person in range(people):
data = raw_input()
#Remove the "#: " in each line and format numbers into ['1','2','3']
data = (data[len(str(person))+2:]).split()
options = len(data)
pairs.update({data:options})
print(pairs)
findPairs(input())
Does anyone know how I can fix this and create my dictionary?
Lists are mutable, and as such - can not be hashed (what happens if the list is changed after being used as a key)?
Use tuples which are immutable instead:
d = dict()
lst = [1,2,3]
d[tuple(lst)] = "some value"
print d[tuple(lst)] # prints "some value"
list is an unhashable type, you need to convert it into tuple before using it as a key in dictionary:
>>> lst = [['25'], ['20','25','28'], ['27','32','37'], ['22']]
>>> print dict((tuple(l), len(l)) for l in lst)
{('20', '25', '28'): 3, ('22',): 1, ('25',): 1, ('27', '32', '37'): 3}

Python dict to string

What is correct way to convert Python dict in single string?
I have example program with code:
keywordsList = {u'roland.luethe1#gmail.com': 2, u'http://www.3ho.de/': 4, u'http://www.kundalini-yoga-zentrum-berlin.de/index.html': 1, u'ergo#ananda-pur.de': 3}
keywordsCount = sorted(keywordsList.items(),key=lambda(k,v):(v,k),reverse=True)
for words in keywordsCount:
print words[0], " - count: ", words[1]
so after I sort my items I get result like this:
http://www.3ho.de/ - count: 4
ergo#ananda-pur.de - count: 3
roland.luethe1#gmail.com - count: 2
http://www.kundalini-yoga-zentrum-berlin.de/index.html - count: 1
And my question is what is correct way to combine all dict stuff with cout in one single string that would look printed out something like:
'http://www.3ho.de/ : 4, ergo#ananda-pur.de : 3, roland.luethe1#gmail.com : 2, http://www.kundalini-yoga-zentrum-berlin.de/index.html : 1'
or something similar but in logic way?
Use str.join() judiciously:
', '.join([' : '.join((k, str(keywordsList[k]))) for k in sorted(keywordsList, key=keywordsList. get, reverse=True)])
Outputs:
>>> ', '.join([' : '.join((k, str(keywordsList[k]))) for k in sorted(keywordsList, key=keywordsList. get, reverse=True)])
u'http://www.3ho.de/ : 4, ergo#ananda-pur.de : 3, roland.luethe1#gmail.com : 2, http://www.kundalini-yoga-zentrum-berlin.de/index.html : 1'
You should really look into collections.Counter() and save yourself having to sort like that. The Counter.most_common() method lists items in reverse sorted order by frequency for you.
I'm not sure about the correct way but you could also do this:
', '.join(' : '.join([a, str(b)]) for a, b in keywordsCount)
use conventional methods,which are simple .This worked for me
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
d=" "
for i in dict:
a=i
b=dict[i]
c=i+":"+dict[i]
d=d+c+'\n'
print d

Categories