How to iterate over a dictionary using for loops? - python

I want to decompress a dictionary and a list into a sentence. For example:
newlist = [1, 2, 3, 4, 5, 6]
new_dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1}
The original sentence is 'My code is broken please help'. The list shows the positions that the words appear within the sentence. The dictionary stores the word and the position that the word associates with.
The goal is to iterate over the dictionary until the matches the number in the list. Once this happens, the key that matches to the value is added to a list. This will continue to happen until there are no more numbers in the list. The list is then converted into a string and printed to the user.
I would imagine that something like this would be the solution:
for loop in range(len(newlist)):
x = 0
for k,v in new_dictionary.items():
if numbers[x] == v:
original_sentence.append(k)
else:
x = x + 1
print(original_sentence)
However, the code just prints an empty list. Is there any way of re-wording or re-arranging the for loops so that the code works?

Invert the dictionary and proceed. Try the following code.
>>> d = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1}
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> d_inv = {v:k for k,v in d.items()}
>>> ' '.join([d_inv[i] for i in numbers])
'my code is broken please help'

I assume you don't want to invert the dictionary, so you can try something like this:
dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1}
numbers = [1, 2, 3, 4, 5, 6]
sentence = []
for number in numbers:
for key in dictionary.keys():
if dictionary[key] == number:
sentence.append(key)
break

Sorted the dict with using the values.
import operator
new_dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1}
sorted_x = sorted(new_dictionary.items(), key=operator.itemgetter(1))
print ' '.join(i[0] for i in sorted_x)
result
'my code is broken please help'
The whole code in single line.
In [1]: ' '.join([item[0] for item in sorted(new_dictionary.items(), key=operator.itemgetter(1))])
Out[1]: 'my code is broken please help'

Related

Adding elements of a list into a dictionary using .get() method

I have a list of elements [1, 2, 5, 2, 3, 7, 5, 8]. I want to put it into a dictionary so it would go "key : how many times it appears in the list", so the dictionary looks something like as follows:
{"1:1", "2:2", "5:2", "3:1", "7:1", "8:1"}
The solution should be applicable to any list.
I did the iteration of the list, but am receiving an error when it comes to adding the elements into the dictionary.
given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
midwayDict = midwayDict.get(element, 0)
print(midwayDict)
All it gives me is " AttributeError: 'int' object has no attribute 'get' ".
Is something wrong with the method I'm using? or should I use a different way?
I saw this being used somewhere a while ago, but I am not being able to find where of how exactly to do this.
The error in your code is
given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
midwayDict = midwayDict.get(element, 0) # <- you are assigning 0 to dict so in next iteration you are accessing .get method on integer so its saying there is no get method on int object
print(midwayDict)
Should be
given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
_ = midwayDict.setdefault(element, 0)
midwayDict[element] += 1
print(midwayDict)
Better is
from collections import Counter
given = (1, 2, 5, 2, 3, 7, 5, 8)
print(Counter(given))
There is only one error in your code.
given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in set(given):
midwayDict[element] = midwayDict.get(element, 0)+1 # edited
print(midwayDict)
The better way to do this is by using dictionary comprehension.
given = (1, 2, 5, 2, 3, 7, 5, 8)
d = {a:given.count(a) for a in set(given)}
print(d)

Store the value of a key-value by its order?

Reading about data structures and have a question.
This is a dictionary:
example = {'the': 8,
'metal': 8,
'is': 23,
'worth': 3,
'many': 3,
'dollars': 2,
'right': 2}
How to store to a variable the value of a key/value pair by order?
For example, how to store the value of the third pair, which is 23?
Tried this, which is not correct:
for k in example:
if k == 3:
a_var = example(k)
If you know the key/values have been inserted in the correct order, you can use islice() to get the third key/value pair. This has the benefit of not needing to create a whole list of values and is a bit simpler than explicitly writing a loop:
from itertools import islice
example = {
'the': 8,
'metal': 8,
'is': 23,
'worth': 3,
'many': 3,
'dollars': 2,
'right': 2
}
key, val = next(islice(example.items(), 2, None))
# 'is', 23
If you only want the value instead of the key/value pair, then of course you can pass values() instead of items() to islice():
val = next(islice(example.values(), 2, None))
# 23
This does what you need:
example = {'the': 8,
'metal': 8,
'is': 23,
'worth': 3,
'many': 3,
'dollars': 2,
'right': 2}
k=0
for key in example:
k+=1
if k == 3:
a_var = example[key]
print(a_var)
Output:
23
If you really think you need this:
def find( example, ordinal):
for k,value in enumerate(example.values()):
if k == ordinal:
return value
or
def find( example, ordinal):
return list(example.values())[ordinal]
a_var=example[list(example.keys())[3-1]]

Adding the values of same keys in one dictionary

I have a Dictionary :
Dict1= {“AAT”: 2, “CCG”: 1, “ATA”: 5, “GCG”: 7, “CGC”: 2, “TAG”: 1, “GAT”: 0, “AAT”: 3, “CCG”: 2, “ATG”: 5, “GCG”: 3, “CGC”: 7, “TAG”: 0, “GAT”: 0}
And I have to sum all the similar triplet codes in a new dictionary.
Output should be like this:
Dict2 = {“AAT”: 5, “CCG”: 3, “ATA”: 5, “GCG”: 10, “CGC”: 9, “TAG”: 1, “GAT”: 0}
How do I proceed with the code?
Dict1 is not a valid dictionary as dictionary keys have to be unique. In general if you have some (non-unique) strings and values assigned to them, you can write
if key in Dict2:
Dict2[key] += val
else
Dict2[key] = val
You are trying to sum up the values of same keys which not possible since python doesn't allow duplicate keys in dictionary. You can check this for reference:
https://www.w3schools.com/python/python_dictionaries.asp

Trouble organizing dictionary by "key" values in descending order in python

I have been trying to organize a dictionary by "key" values and organizing the same list in descending order
ex.
d = {​22698705: [​['James', 'Howlett'],​ ​[2,9,7]]​ ​, ​38698705: [​['Jakie', ' chan'],​ ​[2,9,7]​]​,
​35698705: [​['Jean', 'Grey']​, ​[2,9,7]]​ ​}
the values would have to be organized in descending order and their given "values" would have to follow them in sequence (Ive been instructed to only use .get(), .keys(), .values(), and .pop()). The same list would have to print
{​22698705: [​['James', 'Howlett'],​ ​[2,9,7]]​, ​35698705: [​['Jean', 'Grey']​, ​[2,9,7]]​, 38698705: [​['Jakie', ' chan'],​ ​[2,9,7]​]​ ​}.
How can I do that with the conditions given?
You can try this:
>>>{k: v for k, v in sorted(d.items())}
{22698705: [['James', 'Howlett'], [2, 9, 7]], 35698705: [['Jean', 'Grey'], [2, 9, 7]], 38698705: [['Jakie', ' chan'], [2, 9, 7]]}
I only have python 3.6.9 at hand, but this should do the trick :
>>> d = {22698705: [['James','Howlett'],[2,9,7]], 38698705:[['Jakie','chan'],[2,9,7]], 35698705:[['Jean','Grey'],[2,9,7]]}
>>> r = {k: d[k] for k in sorted(d)}
>>> r
{22698705: [['James', 'Howlett'], [2, 9, 7]], 35698705: [['Jean', 'Grey'], [2, 9, 7]], 38698705: [['Jakie', 'chan'], [2, 9, 7]]}

how to convert an array to a dict in python

Now, I wanna convert an array to a dict like this:
dict = {'item0': arr[0], 'item1': arr[1], 'item2': arr[2]...}
How to solve this problem elegantly in python?
You could use enumerate and a dictionary comprehension:
>>> arr = ["aa", "bb", "cc"]
>>> {'item{}'.format(i): x for i,x in enumerate(arr)}
{'item2': 'cc', 'item0': 'aa', 'item1': 'bb'}
Suppose we have a list of ints:
We can use a dict comprehension
>>> l = [3, 2, 4, 5, 7, 9, 0, 9]
>>> d = {"item" + str(k): l[k] for k in range(len(l))}
>>> d
{'item5': 9, 'item4': 7, 'item7': 9, 'item6': 0, 'item1': 2, 'item0': 3, 'item3': 5, 'item2': 4}
simpleArray = [ 2, 54, 32 ]
simpleDict = dict()
for index,item in enumerate(simpleArray):
simpleDict["item{0}".format(index)] = item
print(simpleDict)
Ok, first line Is the input, second line is an empty dictionary. We will fill it on the fly.
Now we need to iterate, but normal iteration as in C is considered non Pythonic. Enumerate will give the index and the item we need from the array. See this: Accessing the index in Python 'for' loops.
So in each iteration we will be getting an item from array and inserting in the dictionary with a key from the string in brackets. I'm using format since use of % is discouraged. See here: Python string formatting: % vs. .format.
At last we will print. Used print as function for more compatibility.
you could use a dictionary comprehension
eg.
>>> x = [1,2,3]
>>> {'item'+str(i):v for i, v in enumerate(x)}
>>> {'item2': 3, 'item0': 1, 'item1': 2}
Use dictionary comprehension: Python Dictionary Comprehension
So it'll look something like:
d = {"item%s" % index: value for (index, value) in enumerate(arr)}
Note the use of enumerate to give the index of each value in the list.
You can also use the dict() to construct your dictionary.
d = dict(('item{}'.format(i), arr[i]) for i in xrange(len(arr)))
Using map, this could be solved as:
a = [1, 2, 3]
d = list(map(lambda x: {f"item{x[0]}":x[1]}, enumerate(a)))
The result is:
[{'item0': 1}, {'item1': 2}, {'item2': 3}]

Categories