Stripping Newline Characters From Dicts Python 3 - python

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.

Related

How to separate the dictionary with split values

Dictionary is below
a = {'querystring': {'dataproduct.keyword': 'abc,def'}}
How to split into two dictionary with values?
a['querystring'] = {'dataproduct.keyword': 'abc,def'}
Expected out while printing
{'dataproduct.keyword': 'abc'}
{'dataproduct.keyword': 'def'}
Since dictionary is hashmap
[{'dataproduct.keyword': 'abc'} {'dataproduct.keyword': 'def'}]
Disclaimer:
before executing need to check the comma
if a['querystring'] = {'dataproduct.keyword': 'abc'} then no need to split
if a['querystring'] = {'dataproduct.keyword': 'abc,def,efg'} if comma is there then only need to split
[{key: item} for key, value in a['querystring'].items() for item in value.split(',')]
A solution that works with across all top-level entries, not just the entry with key "querystring":
a = {'querystring': {'dataproduct.keyword': 'abc,def'}}
split_a = []
for value in a.values():
for sub_key, sub_value in value.items():
for split_sub_value in sub_value.split(","):
split_a.append({sub_key: split_sub_value})
Resulting value of split_a is [{'dataproduct.keyword': 'abc'}, {'dataproduct.keyword': 'def'}].

How to add values to an existing empty value key dictionary from a file?

I have the following code to create empty dictionary:
empty_dict = dict.fromkeys(['apple','ball'])
empty_dict = {'apple': None, 'ball': None}
I have this empty dictionary.
Now I want to add the values from value.txt which has the following content:
value.txt
1
2
I want the resultant dictionary to be as:
{
"apple" : 1,
"ball" : 2
}
I'm not sure how to update only the value from the dictionary.
You don't really need to make the dict first — it makes it inconvenient to get the order correct. You can just zip() the keys and the file lines and pass it to the dictionary constructor like:
keys = ['apple','ball']
with open(path, 'r') as file:
d = dict(zip(keys, map(str.strip, file)))
print(d)
# {'apple': '1', 'ball': '2'}
This uses strip() to remove the \n characters from the lines in the file.
It's not clear what should happen if you have more lines than keys, but the above will ignore them.

Can I import dictionary items with the same values into a list?

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 to maintain order with finditer ()

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))

Key:Value Pairs from txt file into a dictionary

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]

Categories