these are the inputs:
name:SignalsAndSystems genre:engineering author:Oppenheim
name:calculus genre:mathematics author:Thomas
name:DigitalSignalProcessing genre:engineering author:Oppenheim
and I tried to make dictionaries of each line separated by ":" for example name:SignalsAndSystems.
this is my code but the code makes dictionaries only from the first line of the inputs.
lst_inps = []
for i in range(2):
inp = input()
inp = inp.split(" ")
for item in inp:
attribute, value = item.split(":")
dict.update({attribute: value})
lst_inps.append(dict)
the answer that I'm looking for is:
[
{"name":"SignalsAndSystems", "genre":"engineering", "author":"Oppenheim"} ,
{"name":"calculus", "genre":"mathematics", "author":"Thomas"} ,
{"name":"DigitalSignalProcessing", "genre":"engineering", "author":"Oppenheim"}
]
You aren't creating a dictionary in your for loop. You need to create a dictionary, then update it with your new key value pairs, before appending it to your list.
lst_inps = []
for i in range(3):
new_dict = dict() # create the dictionary here
inp = input()
inp = inp.split(" ")
for item in inp:
attribute, value = item.split(":")
new_dict.update({attribute: value}) # add your key value pairs to the dictionary
lst_inps.append(new_dict) # append your new dictionary to the list
print(lst_inps)
Related
dic = {}
list =[]
def bathSum():
for ZPRODHDR in root.iter('ZPRODHDR'):
for ZPRODITM in ZPRODHDR.iter('ZPRODITM'):
component = ZPRODITM.findtext('COMPONENT')
quantity = ZPRODITM.findtext('QUANTITY')
component = int(component)
quantity = float(quantity)
dic[component] = quantity
list.append(dic)
print('dictionary print', dic)
return(list)
print('list of dictionaries', bathSum())
How I can get output list of dictionaries like in 'dictionary print'?Because it seams to overwrite all values in each dictionary for last loop values.
dictionary print: {60943240: 814.0, 60943245: 557.0}
dictionary print: {60943240: 793.0, 60943245: 482.0}
list of dictionaries: [{60943240: 793.0, 60943245: 482.0}, {60943240: 793.0, 60943245: 482.0}]
The problem is that you are not resetting your dictionary dic at each ZPRODHDR loop. The values are then always updated in the original dictionnary, and always overriding the old values.
This variable is an intermediate variable that should be cleaned at each loop from its values.
You need to move the dic variable declaration inside your first for loop.
list =[]
def bathSum():
for ZPRODHDR in root.iter('ZPRODHDR'):
dic = {}
for ZPRODITM in ZPRODHDR.iter('ZPRODITM'):
component = ZPRODITM.findtext('COMPONENT')
quantity = ZPRODITM.findtext('QUANTITY')
component = int(component)
quantity = float(quantity)
dic[component] = quantity
list.append(dic)
print('dictionary print', dic)
return(list)
print('list of dictionaries', bathSum())
Given text like this:
"$key\n
some value\n
$another_key\n
another longer\n
value\n"
# continue this trend with keys on lines marked by special symbol in this case $
# with corresponding value on the following lines until we hit another key
What would be nice and terse way to transform that into lists like this
keys = ["$key", "$another_key"]
values = ["some value", "another longervalue"]
You can use the $ at the start of a line to identify this is a new key, append it to the keys list and append a new blank string to the values list. Then every time you have a line which doesnt start with a $ you concat that value on to the last element of values as this line must be related to the current key. only when you read a new key do you create a new blank values element.
data = "$key\nsome value\n$another_key\nanother longer\nvalue\n"
keys = []
values = []
for line in data.split('\n'):
if line.startswith('$'):
keys.append(line)
values.append("")
else:
values[-1] += line
print(keys, values)
Output
['$key', '$another_key'] ['some value', 'another longervalue']
text = "$key\nsome value\n$another_key\nanother longer\nvalue"
key = []
value = []
for i in text.split('\n'):
if i[0]=='$':
key.append(i)
else:
value.append(i)
Try this ( assuming text is the variable with text values in it ):
all_text = text.split('\n')
val_tup = [ (val, all_text[i+1]) for i,val in enumerate(all_text) if val.startswith('$') ]
keys, values = [ val[0] for val in val_tup ], [ val[1] for val in val_tup ]
May be like this?
from collections import defaultdict
text = """$key\n
some value\n
$another_key\n
another longer\n
value\n"""
def get_pairs(s):
pairs=defaultdict(str)
current_key=None
for line in s.splitlines():
if line.startswith('$'):
current_key=line
continue
pairs[current_key]+=line
return pairs
get values you need with pairs.keys() and pairs.values()
BTW, the \n is redundant, '''string''' will have \n in it.
s = """$key\n
some value\n
$another_key\n
another longer\n
value\n"""
s = s.split("\n")[:-1] # we know the string ednwith \n
keys, values = [], []
for i in s:
if i[0] == "$" and i[1] !="$":
keys.append(i)
else:
values.append(i)
I'm calculating the average score of people in a dictionary with two-dimensional array and I want to know how to return two people with the same score connected by "and"; EX: name and name
My code:
def bestAverage(inputDict):
dic = {}
for i in inputDict:
if i[0] in dic.keys():
dic[i[0]].append(int(i[1]))
else:
dic[i[0]] = [int(i[1])]
totle_score = 0
print(dic)
for key, value, in dic.items():
for c in value:
totle_score += int(c)
Q = len(value)
avrage = totle_score / Q
dic[key]= [avrage]
print(dic)
My input:
inputDict = [ ["Diane", 20],["Bion",25],["Jack","30"],["Diane","50"] ]
result = bestAverage(inputDict)
OUTCOME:
{'Diane': [35.0], 'Bion': [95.0], 'Jack': [125.0]}
Using the sorted dictionary, you can get the dictionary you want.
Sorry, I think my code is a bit complicated.
dic = {'Diane': [35.0],
'Bion': [95.0],
'Jack': [125.0],
'Diane_2': [35.0],
'Bion_2':[95],
'Diane_3':[35.0],
'John':[10]}
import operator
sorted_dic = sorted(dic.items(), key=operator.itemgetter(0))
new_dic = dict()
preKey = sorted_dic[0][0]
preValue = sorted_dic[0][1]
nms = preKey
for key,value in sorted_dic[1:]:
if(value == preValue):
nms += ' and ' + key
else:
new_dic[nms] = preValue
preKey = key
preValue = value
nms = preKey
new_dic[nms] = preValue
print(new_dic)
OUTCOME:
{'Jack': [125.0], 'John': [10], 'Diane and Diane_2 and Diane_3':
[35.0], 'Bion and Bion_2': [95.0]}
Per the OPs question in the comments, this example now produces a final structure containing entries for only those scores that had multiple people with that same score.
data = {'Diane': [35.0], 'Bion': [95.0], 'Jack': [125.0], 'Sam': [95.0]}
# Here, we create a dict of lists, where the keys are the scores, and the values
# are the names of each person who has that score. This will produce:
#
# {
# 35.0: ['Diane'],
# 95.0: ['Bion', 'Sam'],
# 125.0: ['Jack']
# }
collected = {}
# For each key (name) in the input dict...
for name in data:
# Get the score value out of the array for this name
val = data[name][0]
# If we don't have an entry in our new dict for this score (no key in the dict of that
# score value) then add that entry as the score for the key and an empty array for the value
if val not in collected:
collected[val] = []
# Now that we're sure we have an entry for the score of the name we're processing, add
# the name to the array for that score in the new dict
collected[val].append(name)
# Now we just "flip" each entry in the 'collected' map to create a new dict. We create
# one entry in this dict for each entry in the 'collected' map, where each key is a
# single string where we've combined all of the names with the same score, separated
# by 'and', and each value is the score that those names had.
result = {}
# Now iterate over each of our keys, the unique scores, in our new 'collected' dict...
for val in collected:
# We only want to create an entry in the new dict if the entry we're processing has more than
# just one name in the list of names. So here, we check for that, and skip adding an entry to
# the new dict if there is only one name in the list
if len(collected[val]) == 1:
continue
# Combine the value of this entry, the list of names with a particular score, into a single string
combinedNames = " and ".join(collected[val])
# Add an entry to our 'result' dict with this combined name as the key and the score as the value
result[combinedNames] = val
# Print each combined name string from the resulting structure
for names in result:
print(names)
Output:
Bion and Sam
I'm a beginner to Python. I am begging to learn about functions and files. I need to write a code that will return a list of all the words in dictionary.txt using a function, but I can't seem to figure it out.
Current code
def get_dictionary_wordlist(dic):
dic = open("dictionary.txt", "r")
for word in dic:
return word
You have to make a list and add the words there, then you return it.
def get_dictionary_wordlist(dic):
words = [] # Make a list
dic = open("dictionary.txt", "r")
for word in dic:
words.append() # Add words to the list
return words
this should work:
dictionary = ('Italy', 'pizza'), ('Germany', 'sauerkraut'), ('Spain', 'paella'), ('USA', 'Hamburger') # Opening the dictionary
def listWords(dic): # Creating the function
y = dict(dic) # Making sure dic is a dic
x = [] #creating the list
for key in dic: # Iterating through every item in dic
x.append(key) # Adding the item to the end
return x #returning the results
print listWords(dictionary) #printing the results for the original text, dictionary
While iterating in a for loop, I am trying to append a dictionary item's key to a list if the item has a value of 1.
What I have is:
peeps = {'scoobydoo':0, 'shaggy':0, 'scrappydoo':0, 'velma':1, 'freddy':0, 'daphne':1}
ignore_list = []
for peep in peeps:
if peep == 1:
ignore_list.append(peep)
print(ignore_list)
This however does not give me what I would expect:
['velma', 'daphne']
It prints an empty list:
[]
You didn't check for the value, only for the key itself.
Check the value by accessing it:
for peep in peeps:
if peeps[peep] == 1:
ignore_list.append(peep)
or loop over both keys and values together:
for peep, peep_value in peeps.items():
if peep_value == 1:
ignore_list.append(peep)
You can build the list in one step using a list comprehension here:
ignore_list = [peep for peep, peep_value in peeps.items() if peep_value == 1]
You're iterating over keys not values. So you need to combine the key with the actual dictionary to check if the value of that corresponding key is equal to 1 or not.
peeps = {'scoobydoo':0, 'shaggy':0, 'scrappydoo':0, 'velma':1, 'freddy':0, 'daphne':1}
ignore_list = []
for peep in peeps:
if peeps[peep] == 1:
ignore_list.append(peep)
print(ignore_list)
OR
peeps = {'scoobydoo':0, 'shaggy':0, 'scrappydoo':0, 'velma':1, 'freddy':0, 'daphne':1}
print([key for key,value in peeps.items() if value == 1])
You can iterate through the keys and values of the dictionary to accomplish what you want:
peeps = {'scoobydoo':0, 'shaggy':0, 'scrappydoo':0, 'velma':1, 'freddy':0, 'daphne':1}
ignore_list = []
for key, value in peeps.items():
if value == 1:
ignore_list.append(key)
print(ignore_list)