I have a txt file with key value pairs. It can format (get, retrieve) the pairs from the file in multiple ways, for example:
as line separated strings with colons:
stringa1:stringa2
stringb1:stringb2
or as line separated strings with commas:
stringa1,stringa2
stringb1,stringb2
or as individuals lists of strings:
[stringa1,stringa2]
['stringa1','stringa2']
AND, I can assign each string to a variable with:
for string in list
splitstring=list.split(',')
for item in splitstring:
print (item)
>>>stringa1
>>>stringa2
But I can't figure out how to add those key:value pairs to a dictionary
d[splitstring[0]] = splitstring[1]
should work, where d is a dict. That's the easiest way of adding a key, value pair to a dictionary.
Another way is:
d.update({splitstring[0]: splitstring[1]})
Taking in mind that we are talking about pairs, then
this should work:
mydict = {}
for i in range(0,len(splitstring),2):
mydict[splitstring[i]] = splitstring[i+1]
Related
Imagine having a txt file with like
5843092xxx289421xxx832175xxx...
You have a dictionary with keys correspoding to letters
A am trying to search for each key within the string to output a message.
decoder = {5843092:'a', 289421:'b'}
with open( "code.txt","r") as fileTxt:
fileTxt = fileTxt.readlines()
b = []
for key in decoder.keys():
if key in fileTxt:
b.append(decoder[key])
print(b)
this is what I have I feel like im on the right track but I am missing how to do each iteration maybe?
the goal output in this i.e. would be either a list or string of ab...
There are two problems here:
You have a list of strings, and you're treating it as if it's one string.
You're building your output based on the order the keys appear in the decoder dictionary, rather than the order they appear in the input text. That means the message will be all scrambled.
If the input text actually separates each key with a fixed string like xxx, the straightforward solution is to split on that string:
for line in fileTxt:
print(' '.join(decoder.get(int(key), '?') for key in line.split('xxx')))
I'm importing data from a text file, and then made a dictionary out of that. I'm now trying to make a separate one, with the entries that have the same value only. Is that possible?
Sorry if that's a little confusing! But basically, the text file looks like this:
"Andrew", "Present"
"Christine", "Absent"
"Liz", "Present"
"James", "Present"
I made it into a dictionary first, so I could group them into keys and values, and now I'm trying to make a list of the people who were 'present' only (I don't want to delete the absent ones, I just want a separate list), and then pick one from that list randomly.
This is what I tried:
d = {}
with open('directory.txt') as f:
for line in f:
name, attendance = line.strip().split(',')
d[name.strip()] = attendance.strip()
present_list = []
present_list.append({"name": str(d.keys), "attendance": "Present"})
print(random.choice(present_list))
When I tried running it, I only get:
{'name': '<built-in method keys of dict object at 0x02B26690>', 'attendance': 'Present'}
Which part should I change? Thank you so much in advance!
You can try this:
present_list = [key for key in d if d[key] == "Present"]
first, you have to change the way you the read lines than you can have in your initial dict as key the attendence :
from collections import defaultdict
d = defaultdict(list)
with open('directory.txt') as f:
for line in f.readlines():
name, attendance = line.strip().split(',')
d[attendance.strip()].append(name.strip())
present_list = d["Present"]
print(random.choice(present_list) if present_list else "All absent")
Dict.Keys is a method, not a field. So you must instead do:
d.keys()
This returns an array generator: if you want a comma separated list with square brackets, just calling str() on it is ok. If you want a different formatting, consider ','.join(dict.keys()) to do a simple comma separated list with no square brackets.
UPDATE:
You also have no filtering in place, instead I'd try something like this, where you grab the list of statuses and then compile (new code in BOLD):
d = {}
with open('directory.txt') as f:
for line in f:
name, attendance = line.strip().split(',')
**if name.strip() not in d.keys():
d[attendance.strip()] = [name.strip()]
else:
d[attendance.strip()] = d[attendance.strip()].append(name.strip())**
This way you don't need to go through all those intermediate steps, and you will have something like {"present": "Andrew, Liz, James"}
How would I remove a \n or newline character from a dict value in Python?
testDict = {'salutations': 'hello', 'farewell': 'goodbye\n'}
testDict.strip('\n') # I know this part is incorrect :)
print(testDict)
To update the dictionary in-place, just iterate over it and apply str.rstrip() to values:
for key, value in testDict.items():
testDict[key] = value.rstrip()
To create a new dictionary, you can use a dictionary comprehension:
testDict = {key: value.rstrip() for key, value in testDict.items()}
Use dictionary comprehension:
testDict = {key: value.strip('\n') for key, value in testDict.items()}
You're trying to strip a newline from the Dictionary Object.
What you want is to iterate over all Dictionary keys and update their values.
for key in testDict.keys():
testDict[key] = testDict[key].strip()
That would do the trick.
I want to extract information from a text file and store the data in a directionary. The file records semicolon seperated values. That is, it records one property in one line, and the key and the value are seperated by a semicolon followed by a white space.
def info_file_parser(info_file):
f=open(info_file,'rb')
info={}
for line in f:
line=line.rstrip()
mlist=line.split(": ")
if len(mlist)==2:
info[mlist[0]]=info[mlist[1]]
if __name__='__main__':
fname="/Users/me/info.txt"
info_file_parser(fname)
KeyError: '0'. What's wrong with that? Why can't I create keys by assignment?
You are trying to set a key in your dictionary with a key that doesn't exist.
In the if statement of your function, shouldn't it be:
if len(mlist)==2:
info[mlist[0]]=mlist[1]
this line:
info[mlist[0]]=info[mlist[1]]
tries to store value from info dictonary with key mlist[1] and try this:
info[mlist[0]]=mlist[1]
There seem to be some problem with finditer(), I am repeatedly searching for a pattern in a line using finditer() and I need to maintain the order in which they are gathered, following is my code for it,
names = collections.OrderedDict()
line1 = 'XPAC3出口$<zho>$ASDSA1出口$<chn>$ExitA2$<eng>$YUTY1出口$<fre>'
names = {n.group(2):n.group(1) for n in re.finditer("\$?(.*?)\$<(.*?)>", line1, re.UNICODE)}
And then I am printing it out,
for key, value in names.iteritems():
print key, ' ',value
And the output turns out to be
fre YUTY1出口
chn ASDSA1出口
zho XPAC3出口
eng ExitA2
But I need the following order,
zho XPAC3出口
chn ASDSA1出口
eng ExitA2
fre YUTY1出口
How to go ahead? DO i need to change regex or use something other than finditer()
You rewrite the names dictionary with your dictionary comprehension and regular dictionary doesnt preserve the insert order. To preserve the order return list and give it to OrderedDict like this:
import collection
import re
line1 = 'XPAC3出口$<zho>$ASDSA1出口$<chn>$ExitA2$<eng>$YUTY1出口$<fre>'
names = [(n.group(2), n.group(1)) for n in re.finditer("\$?(.*?)\$<(.*?)>", line1, re.UNICODE)]
names = collections.OrderedDict(names)
for key, value in names.iteritems():
print key, ' ',value
When you say
names = {...}
You are dropping the reference to the empty OrderedDict (which will be garbage collected) and rebinding names to a regular dict (which is unordered of course)
You should pass your matches to the constructor of the OrderedDict
names = collections.OrderedDict((n.group(2), n.group(1)) for n in re.finditer("\$?(.*?)\$<(.*?)>", line1, re.UNICODE))