This code is showing only the last item of a list of dictionaries:
def chooseOneServer():
dara = websvc()
i=0
for item in dara:
for key,value in item.items() :
if key == '1' :
servers = ( ('i',value), )
i +=1
return servers
I've already answered this in the comments of your last question, but here it is again:
def chooseOneServer():
dara = websvc()
i=0
servers = []
for item in dara:
for key,value in item.items() :
if key == '1':
servers.append(('i',value))
i += 1
return servers
You just add each item to a list, rather than overwriting the same tuple each time.
Related
How to return a dictionary with only palindromes of key + value.(assignment)
def isPalindrome(dict1):
newDict = dict1.copy().items()
for key,value in newDict:
result = key + value
for index in range(len(result)):
if result[index] != result[len(result) - 1 - index]:
del dict1[key]
return dict1
dictionary = {
"kaj":"ak",
"ado":"lescent",
"gu":"ug"
}
print(isPalindrome(dictionary))
Current Output:
File "dict.py", line 7, in isPalindrome
del dict1[key]
KeyError: 'ado'
Desired Output:
{'kaj': 'ak','gu': 'ug'}
After deleting the key from the dictionary, the loop keeps on running and may try to delete it a second time, which raises the KeyError you are seeing.
Use a break statement after the del to stop as soon as the entry is deleted.
I'm trying to define a function that receive infinite values in dictonary, but the the exit is taking only the characters of the last 2 key and value.
Any suggestion?
def infinityInvent():
infinityInvent = []
while True:
keys = input(f'Enter a item (or blank to stop): ')
values = input(f'What the value? ')
if keys == '':
break
infinityInvent = dict(zip(keys, values)) # or infinityInvent = {k: v for k, v in zip(keys, values)}
infinityInvent()
You need to set an item in the dict, not redefine the dict:
def infinityInvent():
infinityInvent = {}
while True:
key = input(f'Enter a item (or blank to stop): ')
if key == '':
break
value = input(f'What the value? ')
infinityInvent[key] = value
return infinityInvent
print(infinityInvent())
I've been searching for a solution for hours, but I can't find anything that helps. I'm having a problem converting a list of tuples into a dictionary. I get this error: 'ValueError: dictionary update sequence element #320 has length 1; 2 is required.' Here is a small example of the list of tuples:
[('Heat_equation', 262), ('Portal:Tertiary_Educatio', 262), ('Help:Wiki_markup_example', 262), ('Quantum_mechanics', 262), ('IB_Language_A:_English_Language_and_Literature_Course_Materia', 261), ('Pulmonary_Plethor', 261)]
This is what I want:
{'Heat_equation': 262, 'Portal:Tertiary_Educatio': 262, 'Help:Wiki_markup_example': 262, 'Quantum_mechanics': 262, 'IB_Language_A:_English_Language_and_Literature_Course_Materia': 261, 'Pulmonary_Plethor': 261}
The length is 2 though right? I'm not sure why I'm getting an error. Here is the function where I'm trying to convert the list of tuples into a dictionary:
import urllib.request
import json
import re
def get_url(url):
text = urllib.request.urlopen(url).read().decode()
return text
def get_choice():
try:
print("Select from the following options or press <?> to quit:")
print("1. Display top 1000 articles and views.")
print("2. Display top 100 learning projects.")
choice = input()
choice = int(choice)
if 1 <= choice <= 2:
print()
return choice
except ValueError:
if choice == "":
return None
print("%s is not a valid choice.\n" % choice)
def display_json(text):
lst = []
dictionary = json.loads(text)
for item in dictionary['items']:
for article in item['articles']:
line = (article['article'], article['views'])
lst.append(line)
return lst
def convert_dict(lst):
d = dict()
[d[t[0]].append(t[1]) if t[0] in (d.keys())
else d.update({t[0]: [t[1]]}) for t in lst]
dictionary = {k: v[0] for k, v in d.items()}
return dictionary
def display_dict(dictionary):
print(dictionary)
def learning_project(dictionary):
lst_2 = []
for key, value in dictionary.items():
string = str(key)
match = re.findall(r'([^\/ ]+).*?\w+.*', string)
match.append(value)
tup = tuple(match)
lst_2.append(tup)
return lst_2
def convert(lst_2):
p = dict(lst_2)
print(p)
def main():
while True:
url = "https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikiversity/all-access/2018/01/all-days"
choice = get_choice()
if choice == None:
break
elif choice == 1:
text = get_url(url)
lst = display_json(text)
dictionary = convert_dict(lst)
display_dict(dictionary)
elif choice == 2:
text = get_url(url)
lst = display_json(text)
dictionary = convert_dict(lst)
lst_2 = learning_project(dictionary)
convert(lst_2)
main()
To explain the learning project function, I had a bigger dictionary I needed to parse. So I turned the key into a string and parsed the key with RegEx. I then appended the value to the key and that created rows of lists. Then I turned the rows of lists into tuples, and created a list of tuples. Now I'm just trying to turn this back into a dictionary, but it is not working. Any help is greatly appreciated!
if you are getting errors with p = dict(lst_2) then your input data is not compliant with your requirement. You could make the conversion more robust by ensuring that list elements are always a two entry tuple.
p = dict( (*t,None,None)[:2] for t in lst_2 or [])
This will not fix the data but it may allow you to move forward and perhaps detect the faulty data by finding None key or None values in the resulting dictionary.
data = [('Heat_equation', 262), ('Portal:Tertiary_Educatio', 262),
('Help:Wiki_markup_example', 262), ('Quantum_mechanics', 262),
('IB_Language_A:_English_Language_and_Literature_Course_Materia', 261),
('Pulmonary_Plethor', 261)]
mydict = dict(data)
I am trying to print the results from all 3 names that are input, in a dictionary format. Current code below only prints out the last name. The 2 lines commented out (#) are what I was trying to change around to get it to work, clearly not doing it correctly.
def name():
count = 0
while (count < 5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
#d['first name'].append(v)
#d['last name'].append(v)
count += 1
print(d)
name()
A few things that I'd change:
append each record (dictionary) to a list of entries.
(optional) Use a for-loop rather than a while as less lines of code.
return the entries list, rather than print it as it is a function so I like to have outputs.
So here's the corrected code:
def name():
entries = []
for count in range(5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k, v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
entries.append(d)
return entries
print(name())
For testing purpose, I modified it to just except 2 entries, but we can still see that it works:
Please enter your last name: fish
Please enter your first name: bowl
Please enter your last name: cat
Please enter your first name: mat
[{'Lname': 'fish', 'Fname': 'bowl'}, {'Lname': 'cat', 'Fname': 'mat'}]
Hope! you got it right from Martijin Comments, For reference to other adding this code:
def name():
count = 0
listOfDict = [] #creating empty list
for count in range(3):
dict = {}
qs = dict(Fname = 'first name', Lname = 'last name' )
for k,v in qs.items():
d[k] = input('please enter your {}: '.format(v))
listOfDict.append(d) # adding each item to the list.
count += 1
print listOfDict
name()
This should work:
def name():
count = 0
while (count < 5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
a = input('Please enter your {}: '.format(v))
d[v] = a
count += 1
print(d['first name'],d['last name'])
name()
You can use defaultdict to automatically create lists to store each entered value. The main idea is that you want to append each entered value to a collection of some type (e.g. list).
from collections import defaultdict
number_of_entries = 3
dd = defaultdict(list)
for _ in range(number_of_entries):
for key in ('first name', 'last_name'):
dd[key].append(input('please enter you {}: '.format(key)))
>>> print(dict(dd))
{'first name': ['Adam', 'Milton', 'Irving'],
'last_name': ['Smith', 'Friedman', 'Fisher']}
def parse_actor_data(actor_data):
while 1:
line = actor_data.readline().strip()
if line.count('-') > 5:
break
actor_movie = {}
values = []
actor_name = ''
running_list = []
movie = []
for line in actor_data:
position = line.find(')')
running = line[:position + 1]
value = running.split('\t')
for k in value:
if k != '':
running_list.append(k)
actor_name_list = value[0].split(',')
actor_name = actor_name_list[0] + actor_name_list[-1]
for i in range(len(running_list)):
if value[0] == running_list[i]:
position2 = i
movie = running_list[position2+1:]
actor_movie[actor_name] = movie
check = actor_movie.keys()
for c in range(len(check)):
if len(check[c]) < 1:
actor_movie.pop(check[c])
return actor_movie
Problem I'm having now is that only the first item of movie is added into the actor_movie anyone can help? i tried so long for this already i seriously have no idea why isn't this working...
Every time you run:
actor_movie[actor_name] = movie
you're overwriting the last movie that was associated with that actor. Try something like this instead where you're storing a list of movies, not just a single value:
try:
actor_movie[actor_name].append(movie)
except KeyError:
actor_movie[actor_name] = [movie]
There are other ways (defaultdict, dict.setdefault, etc.) to do the same thing but that should get you up and running.