?
Solved

Allow user to choose items in two Python dictionaries to build a third one

Posted on 2014-04-15
1
Medium Priority
?
196 Views
Last Modified: 2014-04-15
Hi there!

I am trying to build a function that compares fields_csv and fields_db and asks the users which value he's like to import.

I've built it with success with lists but I need both values and keys so i've chosen dictionaries for the job.

I thought something similar and read the subject doing exercises on Code Academy but I still can't get how to handle it:

csv_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'new note'}
db_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'old note'}
import_fields = {}

def fields_check(csv_fields, db_fields):
    for csv_key, csv_value in csv_fields.iteritems():
        for db_key, db_value in db_fields.iteritems():
            if csv_value == db_value:
                import_fields[csv_key] = csv_value
            elif csv_value != db_value:
                while True:
                    print ""
                    print "1) Field in csv: " + csv_value
                    print "2) Field in db: " + db_value
                    print ""
                    user_answer = str(raw_input("Which do you want to keep? [1 o 2]: "))
                    print ""
                    if user_answer == "1":
                        import_fields[csv_key] = csv_value
                        print "You dedided to keep the field name: " + csv_key + " with value: " + csv_value
                        break
                    elif user_answer == "2":
                        import_fields[db_key] = db_value
                        print "You dedided to keep the field name: " + db_key + " with value: " + db_value
                        break
            else:
                print "Error!"

fields_check(csv_fields, db_fields)
print import_fields

Open in new window

0
Comment
Question by:ltpitt
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 29

Accepted Solution

by:
pepr earned 2000 total points
ID: 40002567
I guess that both csv and db should do have the same keys, and only the values may differ. If it is the case then you want to loop through all keys, and it does not matter whether you get them from the csv_fields or the db_fields. Then you get the values for the key from both dictionaries. And then ask the user only when the values differ, as you did.

To summarize, you need only one for loop to go through the keys.
csv_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'new note'}
db_fields = {'name' : 'john', 'surname' : 'white', 'note' : 'old note'}
import_fields = {}

def fields_check(csv_fields, db_fields):
    for k in csv_fields:
        csv_value = csv_fields[k]
        db_value = db_fields[k]
        if csv_value == db_value:
            import_fields[k] = csv_value
        elif csv_value != db_value:
            while True:
                print "The key is:", k
                print
                print "1) Field in csv:", csv_value
                print "2) Field in db: ", db_value
                print
                user_answer = raw_input("Which do you want to keep? [1 o 2]: ")
                print
                if user_answer == "1":
                    import_fields[k] = csv_value
                    print "You dedided to keep the field name:", k, 
                    print "with value:", csv_value
                    break
                elif user_answer == "2":
                    import_fields[k] = db_value
                    print "You dedided to keep the field name:", k, "with value:", db_value
                    break
                else:
                    print "Error!"


fields_check(csv_fields, db_fields)
print import_fields

Open in new window

The csv_value can be extracted via .iteritems() as you did in your code to remove the next line. I did not do that to emphasise symmetry.

If the keys may differ in boh dictionaries, it is possible to iterate through the unified set of the keys from both dictionaries. In this case, the value must be extracted via:
    csv_value = csv_fields.get(k, None)

Open in new window

where None is the default value if the key is not in the dictionary.

It is usually better to use the print command with arguments separated by commas. The reason is that if the argument is not a string, it is converted to the string representation automatically by the print. On the other hand the plus operator needs the strings on both sides.

The raw_input() result need not to be converted to str because it already is str.

If the print command is too long, you can spit it to two prints where the first one ends with the trailing comma -- as shown when printing the csv choice. The comma in print adds the separating space automatically.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Suggested Courses
Course of the Month11 days, 1 hour left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question