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]]
Related
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
I want to be able to index a dictionary and replace its values for particular keys by using keys from within a specific list and writing values to those keys from that list.
Code
dicty = {"NDS" : 1, "TCT": 2, "ET" : 3, "ACC" : 4,"Ydist" : 5, "Diam" : 6}
tem = ["NDS", "TCT"]
circ = ["ET", "ACC"]
jit = ["Ydist", "Diam"]
def cal_loop(cal_vers):
if cal_vers == temp_calibration:
print("DO TEMP CALIBRATION")
tem_results = [19,30]
dict_keys = tem
dicty[[dict_keys][0]] = tem_results[0]
print(dicty["NDS"])
temp_calibration = 6
cal_loop(temp_calibration)
print(dicty)
Traceback
Desired output
{'NDS': 19, 'TCT': 2, 'ET': 3, 'ACC': 4, 'Ydist': 5, 'Diam': 6}
#I also want to know how to do both keys in the list given e.g.
{'NDS': 19, 'TCT': 30, 'ET': 3, 'ACC': 4, 'Ydist': 5, 'Diam': 6}
tem = ["NDS", "TCT"]
tem_results = [19,30]
for k, v in zip(tem, tem_results):
dicty[k] = v
The issue is with dicty[[dict_keys][0]] = tem_results[0]. You have to loop thought the two lists and update the dictionary or instead create a new dictonary and update the existing one using:
dicty.update({k: v for k, v in zip(tem, tem_results)})
I want to create a dictionary by using a loop or similar technique. Something like the below variable assignment is possible.
my_dict = {v:int(v*random()) for v in range(10)}
Though the question I am stuck at- How can I generate similar names for the item keys? Giving an example below:
{'Item-1': 1, 'Item-2':3, 'Item-3':3 ....}
Thanks in advance!
from random import random
my_dict = {f'item-{v+1}': int(v*random()) for v in range(10)}
print(my_dict)
Output:
{'item-1': 0, 'item-2': 0, 'item-3': 1, 'item-4': 1, 'item-5': 0, 'item-6': 3, 'item-7': 2, 'item-8': 4, 'item-9': 6, 'item-10': 2}
This uses an f-string to create the key, the corresponding value is randomly generated like in your question.
You can use list comprehension in dictionaries too.
from random import randint
dic = {f"item-{i}": randint(0, 10) for i in range(1, 11)}
print(dic)
Create keys and values and add to my_dict in a loop
my_dict = {}
for v in range(10): my_dict[f'Item-{v}'] = v
print(my_dict)
{'Item-0': 0, 'Item-1': 1, 'Item-2': 2, 'Item-3': 3, 'Item-4': 4, 'Item-5': 5, 'Item-6': 6, 'Item-7': 7, 'Item-8': 8, 'Item-9': 9}
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'
dico = {"dico": {1:"bailler",2:"bailler",3:"percer",4:"calculer",5:"calculer",6:"trouer",7:"bailler",8:"découvrir",9:"bailler",10:"miser",11:"trouer",12:"changer"}}
I have a big dictionary of dictionaries like that. I want to put identic elements together in sets. So create a kind of condition which will say if the values of "dico" are equal put them in a set():
b=[set(1,2,7,9),set(3),set(4,5),set(6,11),set(8),set(10),set(12)]
I don't know if that question has already been asked but as a new pythonner I don't have all the keys... ^^
Thank you for you answers
I would reverse your dictionary and have the value a set(), then return all the values.
>>> from collections import defaultdict
>>>>my_dict= {"dico": {1:"bailler",2:"bailler",3:"percer",4:"calculer",5:"calculer",6:"trouer",7:"bailler",8:"découvrir",9:"bailler",10:"miser",11:"trouer",12:"changer"}}
>>> my_other_dict = defaultdict(set)
>>> for dict_name,sub_dict in my_dict.iteritems():
for k,v in sub_dict.iteritems():
my_other_dict[v].add(k) #the value, i.e. "bailler" is now the key
#e.g. {"bailler":set([1,2,9,7]),...
>>> [v for k,v in my_other_dict.iteritems()]
[set([8]), set([1, 2, 9, 7]), set([3]), set([4, 5]), set([12]), set([11, 6]), set([10])]
Of course as cynddl has pointed out, if your index in a list will always be the "key", simply enumerate a list and you won't have to store original data as a dictionary, nor use sets() as indices are unique.
You should write your data this way:
dico = ["bailler", "bailler", "percer", "calculer", "calculer", "trouer", "bailler", "découvrir", "bailler", "miser", "trouer", "changer"]
If you want to count the number of identic elements, use collections.Counter:
import collections
counter=collections.Counter(dico)
print(counter)
which returns a Counter object:
Counter({'bailler': 4, 'calculer': 2, 'trouer': 2, 'd\xc3\xa9couvrir': 1, 'percer': 1, 'changer': 1, 'miser': 1})
The dict.setdefault() method can be handy for tasks like this, as well as dict.items() which iterates through the (key, value) pairs of the dictionary.
>>> dico = {"dico": {1:"bailler",2:"bailler",3:"percer",4:"calculer",5:"calcul
er",6:"trouer",7:"bailler",8:"découvrir",9:"bailler",10:"miser",11:"trouer",12:"
changer"}}
>>> newdict = {}
>>> for k, subdict in dico.items():
... newdict[k] = {}
... for subk, subv in subdict.items():
... newdict[k].setdefault(subv, set()).add(subk)
...
>>> newdict
{'dico': {'bailler': {1, 2, 9, 7}, 'miser': {10}, 'découvrir': {8}, 'calculer':
{4, 5}, 'changer': {12}, 'percer': {3}, 'trouer': {11, 6}}}
>>> newdict['dico'].values()
dict_values([{1, 2, 9, 7}, {10}, {8}, {4, 5}, {12}, {3}, {11, 6}])